gpt4 book ai didi

python - 如何在带有漂亮汤的div中选择一类div?

转载 作者:太空狗 更新时间:2023-10-29 20:15:43 26 4
gpt4 key购买 nike

我在 div 标签中有一堆 div 标签:

<div class="foo">
<div class="bar">I want this</div>
<div class="unwanted">Not this</div>
</div>
<div class="bar">Don't want this either
</div>

所以我使用 python 和 beautiful soup 来分离东西。只有当它被包裹在“foo”类 div 中时,我才需要所有“bar”类。这是我的代码

from bs4 import BeautifulSoup
soup = BeautifulSoup(open(r'C:\test.htm'))
tag = soup.div
for each_div in soup.findAll('div',{'class':'foo'}):
print(tag["bar"]).encode("utf-8")

或者,我试过:

from bs4 import BeautifulSoup
soup = BeautifulSoup(open(r'C:\test.htm'))
for each_div in soup.findAll('div',{'class':'foo'}):
print(each_div.findAll('div',{'class':'bar'})).encode("utf-8")

我做错了什么?如果我可以从选择中删除“不需要的”div 类,我会很高兴只使用一个简单的 print(each_div)。

最佳答案

您可以使用 find_all()搜索每个 <div>带有 foo 的元素作为属性,对它们中的每一个使用 find()对于那些 bar作为属性,例如:

from bs4 import BeautifulSoup
import sys

soup = BeautifulSoup(open(sys.argv[1], 'r'), 'html')
for foo in soup.find_all('div', attrs={'class': 'foo'}):
bar = foo.find('div', attrs={'class': 'bar'})
print(bar.text)

像这样运行它:

python3 script.py htmlfile

产生:

I want this

更新:假设可能存在多个 <div>带有 bar 的元素属性,以前的脚本将不起作用。它只会找到第一个。但是你可以得到他们的后代并迭代他们,比如:

from bs4 import BeautifulSoup
import sys

soup = BeautifulSoup(open(sys.argv[1], 'r'), 'html')
for foo in soup.find_all('div', attrs={'class': 'foo'}):
foo_descendants = foo.descendants
for d in foo_descendants:
if d.name == 'div' and d.get('class', '') == ['bar']:
print(d.text)

输入如下:

<div class="foo">
<div class="bar">I want this</div>
<div class="unwanted">Not this</div>
<div class="bar">Also want this</div>
</div>

它将产生:

I want this
Also want this

关于python - 如何在带有漂亮汤的div中选择一类div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22217713/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com