简体   繁体   中英

Find tag preceding another tag BeautifulSoup

find_previous gives the tag preceding a specific tag, but I want to find text in <b> tag just above <table> tag.

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


"

The expected output should be Output . How can I do this?

With the HTML you have, the following would work:

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)

Which would display the <b> tag as:

Output

Another way could be something like:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM