Python 查找另一个标记前面的标记
find_previous给出了特定标记前面的标记,但我想在标记上面的标记中查找文本 预期的输出应该是输出。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> .....
我如何才能做到这一点?使用您拥有的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中唯一的一个吗?