python - 用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 来处理这个问题。多个div
andspan
存在,这使得在没有 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]')
但是,这会返回一个空列表。
解决方案
用于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
推荐阅读
- android - 科尔多瓦 bluetoothSerial.discoverUnpaired 不会在 android 10 中发出值
- windows - 是否有任何方法可以使用 shell 命令获取 Windows 设备中所有已安装应用程序的详细信息
- ms-access - 使用 MS Access 查询(BOM 资源管理器的排序)
- sql - 如何在 SQL Server SQL Query 中进行多个左连接
- javascript - JavaScript 循环将数据附加到 formData - 递增变量显示与 formData 中的每个循环相同
- kivy - 在 Kivy 中使用构建器
- reactjs - 带有嵌套查询结果的 ApolloClient v3 fetchMore
- java - 为keycloak角色动态定义springboot antmatcher
- python-3.x - 根据数据框中的条件拆分列
- python - Excel中的for循环Python OpenPyXL