BeautifulSoup怎么获取子标签

avatar
作者
筋斗云
阅读量:0

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

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

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

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

from bs4 import BeautifulSoup  html = ''' 

子标签1

子标签2

'''
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子标签,并打印出它们的文本内容。

    广告一刻

    为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!