使用解析器从Span提取行内数据

问题描述 投票:0回答:1

我希望能够从内联范围中提取一些数据,但是在获取数据时遇到了麻烦。

下面是代码部分,我正在尝试获取data-score =“ 5”。该号码将根据客户评论而更改。

HTML部分:

<span aria-label="5 star review" class="jdgm-rev__rating" data-score="5" tabindex="0">

有人帮助我的Python3部分可以提取类选择器,但想获取不是类的数据。

部分Python代码:

with requests.Session() as s:
    r = s.get(start_url).json()
    soup = bs(r['html'], 'lxml')
    ratings.extend([i.text for i in soup.select('.jdgm-rev__rating')])
    titles.extend([i.text for i in soup.select('.jdgm-rev__title')])
    total_pages = int(soup.select_one('.jdgm-paginate__last-page')['data-page'])
python python-3.x html-parsing
1个回答
0
投票

您要查找的是跨度的属性。

>>> from bs4 import BeautifulSoup
>>> 
>>> soup = BeautifulSoup('<p><span aria-label="5 star review" class="jdgm-rev__rating" data-score="5" tabindex="0">')
>>> soup.find('span').attrs
{'aria-label': '5 star review', 'class': ['jdgm-rev__rating'], 'data-score': '5', 'tabindex': '0'}
>>> 
>>> int(soup.find('span').attrs['data-score'])
5
© www.soinside.com 2019 - 2024. All rights reserved.