使用BeautifulSoup获取兄弟标签可以通过以下方式实现:
.next_sibling
和 .previous_sibling
方法获取下一个兄弟标签和上一个兄弟标签。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')
first_div = soup.find(id='first')
second_div = first_div.next_sibling.next_sibling
third_div = second_div.next_sibling
print(first_div.text) # Output: First div
print(second_div.text) # Output: Second div
print(third_div.text) # Output: Third div
.find_next_sibling()
和 .find_previous_sibling()
方法来查找下一个兄弟标签和上一个兄弟标签。second_div = first_div.find_next_sibling('div')
third_div = second_div.find_next_sibling('div')
print(first_div.text) # Output: First div
print(second_div.text) # Output: Second div
print(third_div.text) # Output: Third div
这些方法可以帮助你在BeautifulSoup中获取兄弟标签。