gpt4 book ai didi

python - 使用 beautifulsoup 通过 div 标签查找 div 文本

转载 作者:搜寻专家 更新时间:2023-10-31 23:15:55 24 4
gpt4 key购买 nike

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

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

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

我的想法是这样的:

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]')

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

最佳答案

使用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

关于python - 使用 beautifulsoup 通过 div 标签查找 div 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56252664/

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