Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 查找另一个标记前面的标记_Python_Beautifulsoup - Fatal编程技术网

Python 查找另一个标记前面的标记

Python 查找另一个标记前面的标记,python,beautifulsoup,Python,Beautifulsoup,find_previous给出了特定标记前面的标记,但我想在标记上面的标记中查找文本 预期的输出应该是输出。 我如何才能做到这一点?使用您拥有的HTML,以下内容将起作用: from bs4 import BeautifulSoup html = """<h2>Hi</h2> <b>I am here</b> <b>Output</b> <h2>Hi</h2> <table> .....

find_previous给出了特定标记前面的标记,但我想在标记上面的标记中查找文本

预期的输出应该是输出。
我如何才能做到这一点?

使用您拥有的HTML,以下内容将起作用:

from bs4 import BeautifulSoup

html = """<h2>Hi</h2>
<b>I am here</b>
<b>Output</b>
<h2>Hi</h2>
<table>
.....
</table>"""                

soup = BeautifulSoup(html, "html.parser")
print(soup.table.find_previous('b').text)

使用您拥有的HTML,以下内容将起作用:

from bs4 import BeautifulSoup

html = """<h2>Hi</h2>
<b>I am here</b>
<b>Output</b>
<h2>Hi</h2>
<table>
.....
</table>"""                

soup = BeautifulSoup(html, "html.parser")
print(soup.table.find_previous('b').text)

另一种方式可能是:

from bs4 import BeautifulSoup

html ='''
<h2>Hi</h2>
<b>I am here</b>
<b>Output</b>
<h2>Hi</h2>
<table>
.....
</table>
'''               
soup = BeautifulSoup(html, "lxml")
item = soup.select_one("table").find_previous_sibling("b").text
print(item)

另一种方式可能是:

from bs4 import BeautifulSoup

html ='''
<h2>Hi</h2>
<b>I am here</b>
<b>Output</b>
<h2>Hi</h2>
<table>
.....
</table>
'''               
soup = BeautifulSoup(html, "lxml")
item = soup.select_one("table").find_previous_sibling("b").text
print(item)

请添加到目前为止的代码。这是HTML中唯一的代码吗?请添加到目前为止的代码。这是HTML中唯一的一个吗?