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

标签 python beautifulsoup

我在 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/

相关文章:

python - BeautifulSoup:如果未找到 HTML 元素,则返回 None

Python:使用for循环输出ASCII表

python - 如何将单行美化为多行?

Python 和 BeautifulSoup - 在带有 <dt> 和 <dd> 标签的 div 中指定字段时遇到问题

python - 我怎样才能从 BeautifulSoup 中获取 CData

python - 无法从网页中抓取不同项目的标题

python - numpy - 使用一些预先计算的映射有效地将值从矩阵复制到矩阵

python - 按年份分组删除一些变量

python - 在 Mac 上安装 MySQLdb

python - 捕获 psycopg2 中的任何错误而不明确列出它们