使用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中獲取兄弟標簽。