首页 > 解决方案 > 使用 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的紧密副本

标签: pythonhtmlparsingbeautifulsoupextract

解决方案


只使用 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']]

推荐阅读