【问题标题】:Extract Inline Data From Span With Parser使用 Parser 从 Span 中提取内联数据
【发布时间】:2020-04-17 16:24:12
【问题描述】:

我希望能够从内联 span 中提取一些数据,但无法将数据提取出来。

以下是代码部分,我正在尝试获取 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】:

    你要找的是跨度的属性。

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

    【讨论】:

    • 这是否适用于 data-score="5" 数字会因审查而异的事实?这是整个代码。 pastebin.com/1wEfLHsM
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 2018-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多