使用BeautifulSoup的tag.children获取所有子元素,然后使用列表切片操作只保留奇数索引的元素。
以下是一个示例代码:
from bs4 import BeautifulSoup
html = """
Paragraph 1
Paragraph 2
Paragraph 3
Paragraph 4
Paragraph 5
"""
soup = BeautifulSoup(html, 'html.parser')
div_tag = soup.find('div')
odd_children = list(div_tag.children)[1::2] # 使用列表切片操作获取奇数索引的元素
for child in odd_children:
print(child)
输出结果为:
Paragraph 2
Paragraph 4
这样就只获取了奇数索引的子元素。