温馨提示×

BeautifulSoup怎么获取子标签

小亿
89
2024-05-14 11:09:13
栏目: 编程语言

要获取子标签,可以使用BeautifulSoup的find()或find_all()方法来查找特定的子标签。

例如,假设我们有以下HTML代码:

<div id="parent">
    <p>子标签1</p>
    <p>子标签2</p>
</div>

我们可以使用BeautifulSoup来获取parent标签的所有子标签p:

from bs4 import BeautifulSoup

html = '''
<div id="parent">
    <p>子标签1</p>
    <p>子标签2</p>
</div>
'''

soup = BeautifulSoup(html, 'html.parser')
parent_tag = soup.find('div', {'id': 'parent'})
child_tags = parent_tag.find_all('p')

for tag in child_tags:
    print(tag.text)

输出结果为:

子标签1
子标签2

在这个例子中,我们首先使用find()方法找到id为parent的div标签,然后使用find_all()方法找到所有的p子标签,并打印出它们的文本内容。

0