可以使用 find_all 方法的参数来指定要查找的标签或特定属性,也可以使用 find_parents 和 find_next_siblings 方法来查找其它的块。
代码示例:
from bs4 import BeautifulSoup
html = """
Title One
paragraph 1
paragraph 2
Title Two
paragraph 3
"""
# 使用 find_all 方法查找所有的 p 标签,并打印它们的内容
soup = BeautifulSoup(html, 'html.parser')
ps = soup.find_all('p')
for p in ps:
print(p.string)
# 使用 find_all 方法的参数来指定查找的标签
soup = BeautifulSoup(html, 'html.parser')
div = soup.find('div', class_='book')
ps = div.find_all('p')
for p in ps:
print(p.string)
# 使用 find_parents 方法找到所有包含 p 标签的元素,再使用 find_all 方法查找它们的兄弟元素
soup = BeautifulSoup(html, 'html.parser')
ps = soup.find_all('p')
for p in ps:
for parent in p.find_parents():
siblings = parent.find_next_siblings()
for sibling in siblings:
if sibling.name == 'p':
print(sibling.string)