首页 > 解决方案 > 用beautifulsoup通过div标签查找div文本

问题描述

假设以下 html 片段,我想从中提取与标签“价格”和“发货自”相对应的值:

<div class="divName">
    <div>
        <label>Price</label>
        <div>22.99</div>
    </div>
    <div>
        <label>Ships from</label>
        <span>EU</span>
    </div>
</div>

这是较大的 html 文件的一部分。假设在某些文件中存在“Ships from”标签,有时不存在。由于 html 内容的可变性,我想使用类似方法的 BeautifulSoup 来处理这个问题。多个divandspan存在,这使得在没有 id 或类名的情况下很难选择

我的想法,是这样的:

t = open('snippet.html', 'rb').read().decode('iso-8859-1')
s = BeautifulSoup(t, 'lxml')
s.find('div.divName[label*=Price]')
s.find('div.divName[label*=Ships from]')

但是,这会返回一个空列表。

标签: pythonhtmlweb-scrapingbeautifulsouppython-3.6

解决方案


用于select查找label然后使用find_next_sibling().text

前任:

from bs4 import BeautifulSoup

html = """<div class="divName">
    <div>
        <label>Price</label>
        <div>22.99</div>
    </div>
    <div>
        <label>Ships from</label>
        <span>EU</span>
    </div>
</div>"""

soup = BeautifulSoup(html, "html.parser")
for lab in soup.select("label"):
    print(lab.find_next_sibling().text)

输出:

22.99
EU

推荐阅读