Skip to main content
 首页 » 编程设计

python之查找另一个标签之前的标签 BeautifulSoup

2025年05月04日16bhlsheji

find_previous给出特定标签前面的标签,但我想在 <b> 中查找文本<table> 正上方的标签标签。

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

预期输出应为 Output . 我该怎么做?

请您参考如下方法:

调用 find_previous() 可以先用来定位之前的<b>标签。从那里可以使用 .text 提取元素的文本或 .get_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) 

这将显示 <b>标记为:

Output