python - 使用 Soup 从 HTML 属性中提取值
问题描述
这是我使用的完整 html。
这是上述 HTML 的简化版本:
<table class="premium">
<tr class="retailer top-offer" data-pricer="47.84" saler-id="123">...</td>
<tr class="retailer" data-pricer="57.11" saler-id="234">...</td>
</table>
<table class="basic-supp">
<tr class="retailer top-offer" data-pricer="41.87" saler-id="456">...</td>
<tr class="retailer" data-pricer="58.12" saler-id="567">...</td>
</table>
从带有TR标签的class="basic-supp"和data-pricer="..."属性的 TABLE 中,我需要提取值。
我在简化的 html 上尝试了这种方法:
from bs4 import BeautifulSoup
with open('file.html', 'r') as f:
contents = f.read()
soup = BeautifulSoup(contents, 'lxml')
tags = soup.find_all('tr')
for tag in tags:
print(tag.attrs['data-pricer'])
> 47.84
> 57.11
> 41.87
> 58.12
这几乎是我需要的,除了它从两个表而不是带有class="basic-supp"的表中获取值的事实。知道如何解决吗?
主要问题是它在我上面发布的完整 html 上根本不起作用。错误:
print(tag.attrs['data-pricer'])
KeyError: 'data-pricer'
有人可以给我建议吗?
感谢您的时间!
PS这甚至不是帖子Extracting an attribute value with beautifulsoup的紧密副本
解决方案
只使用 css 选择器更容易:
data = []
for tr in soup.select('table.basic-supp tr'):
data.append([tr['data-pricer'],tr['saler-id'] ])
print(data)
或者,如果你想使用极端的列表推导,一个单行:
[[tr['data-pricer'],tr['saler-id']] for tr in soup.select('table.basic-supp tr')]
在任何一种情况下,输出都应该是:
[['41.87', '456'], ['58.12', '567']]
推荐阅读
- azure-ad-b2c - SAML 注销 - Azure B2C
- javascript - 有没有办法在 PrimeNG P-dropdown 值集中添加分隔符或分隔符
- r - R中的最后一次观察结果和最后一次观察结果向后进行
- android - Android 模拟器 - 升级后如何运行 Chrome 应用
- sql - Excel 中的 SQL:无法调用声明的变量
- sql-server - 有没有办法为 SQL Server 中的排序操作设置默认排序规则?或 SQL Server 2019 中的 oracle NLS_SORT 等效项
- visual-studio-code - Visual Studio Code 文件过滤器行为
- python - 使用 FiPy 在 1D 柱坐标上求解 PDE
- javascript - jQuery Validator Form Plugin 在验证之后但在提交之前显示消息
- r - 如何使用ggplot2将子组点图(3)集中在分组箱线图(2)上?