【问题标题】:How can i extract a number between two elements? (webscraping)如何提取两个元素之间的数字? (网页抓取)
【发布时间】:2020-06-12 23:07:20
【问题描述】:

我从网络抓取开始,我想提取strong 元素之间的数字。

我正在使用 python 3.8 和 beautifulsoup

<li class="price-current">
    <span class="price-current-label">
    </span>$<strong>409</strong><sup>.99</sup> <a class="price-current-num" href="https://www.newegg.com/gigabyte-radeon-rx-5700-xt-gv-r57xtgaming-oc-8gd/p/N82E16814932208?Item=N82E16814932208&amp;buyingoptions=New">(5 Offers)</a>
    <span class="price-current-range">
        <abbr title="to">–</abbr>
    </span>
</li>

【问题讨论】:

  • 你的代码是什么样的?什么是“强”元素,它们之间的“数”是多少?请看how to ask

标签: javascript python html beautifulsoup


【解决方案1】:

要获取&lt;strong&gt;...&lt;/strong&gt;之间的数字,可以使用这个例子:

from bs4 import BeautifulSoup

txt = '''<li class="price-current">
    <span class="price-current-label">
    </span>$<strong>409</strong><sup>.99</sup> <a class="price-current-num" href="https://www.newegg.com/gigabyte-radeon-rx-5700-xt-gv-r57xtgaming-oc-8gd/p/N82E16814932208?Item=N82E16814932208&amp;buyingoptions=New">(5 Offers)</a>
    <span class="price-current-range">
        <abbr title="to">–</abbr>
    </span>
</li>'''

soup = BeautifulSoup(txt, 'html.parser')

print( soup.select_one('.price-current strong').text )

打印:

409

要获得全部价格(包括.的价格),您可以使用re模块:

import re

price = re.search(r'\$\d+.?\d*', soup.select_one('.price-current').text)
if price:
    print(price.group())

打印:

$409.99

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2022-01-21
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 2018-02-07
    相关资源
    最近更新 更多