要查找特定元素后的元素,不一定是兄弟或子元素,可以使用BeautifulSoup的find_all_next()
方法。
下面是一个示例代码:
from bs4 import BeautifulSoup
# 假设HTML文档如下
html = '''
Title
Paragraph 1
Paragraph 2
Subtitle
Paragraph 3
Paragraph 4
'''
# 创建BeautifulSoup对象
soup = BeautifulSoup(html, 'html.parser')
# 查找元素后的所有
元素
h1_element = soup.find('h1')
p_elements = h1_element.find_all_next('p')
# 打印结果
for p in p_elements:
print(p.text)
运行上述代码,输出结果如下:
Paragraph 1
Paragraph 2
Paragraph 3
Paragraph 4
在上面的代码中,我们首先找到元素,然后使用
find_all_next()
方法查找该元素后面的所有元素。最后,使用一个循环打印出每个
元素的文本内容。