温馨提示×

BeautifulSoup怎么获取前后兄弟标签

小亿
131
2024-05-14 11:11:16
栏目: 编程语言

要获取BeautifulSoup中标签的前后兄弟标签,可以使用BeautifulSoup提供的find_previous_sibling()find_next_sibling()方法。

例如,如果我们有一个HTML文档如下:

<html> <body> <div id="first">First div</div> <div id="second">Second div</div> <div id="third">Third div</div> </body> </html> 

我们想获取second标签的前后兄弟标签,可以使用以下代码:

from bs4 import BeautifulSoup html = """ <html> <body> <div id="first">First div</div> <div id="second">Second div</div> <div id="third">Third div</div> </body> </html> """ soup = BeautifulSoup(html, 'html.parser') second_div = soup.find(id='second') previous_sibling = second_div.find_previous_sibling() next_sibling = second_div.find_next_sibling() print("Previous sibling:", previous_sibling) print("Next sibling:", next_sibling) 

这样我们就可以获取到second标签的前一个兄弟标签和后一个兄弟标签。

0