要获取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
标签的前一个兄弟标签和后一个兄弟标签。