我正在抓取类似于以下内容的 html 数据:
<div class="target-content">
<p id="random1">
"the content of the p"
</p>
<p id="random2">
"the content of the p"
</p>
<p>
<q class="semi-predictable">
"q tag content that I don't want
</q>
</p>
<p id="random3">
"the content of the p"
</p>
</div>
我的目标是获得所有<p>
标签及其内容,同时能够排除<q>
标签及其内容。目前,我得到了所有<p>
使用以下方法标记:
contentlist = soup.find('div', class_='target-content').find_all('p')
我的问题是在我找到所有结果集之后<p>
标签,如何过滤掉单个<p>
及其内容,其中包含<q>
?
值得注意的是:得到结果集后soup.find('div', class_='target-content')find_all('p')
,我迭代地添加每个<p>
通过以下方式从结果集到列表:
content = ''
for p in contentlist:
content += str(p)
你可以直接跳过p
标签具有q
里面的标签:
for p in soup.select('div.target-content > p'):
if p.q: # if q is present - skip
continue
print(p)
where p.q
是一个捷径p.find("q")
. div.target-content > p
is a CSS 选择器 https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors这将匹配所有p
直接子标签div
元素与target-content
class.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)