首页 > 解决方案 > 如何提取两个元素之间的数字?(网页抓取)

问题描述

我从网络抓取开始,我想提取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">–&lt;/abbr>
    </span>
</li>

标签: javascriptpythonhtmlbeautifulsoup

解决方案


要获取 之间的数字<strong>...</strong>,您可以使用以下示例:

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">–&lt;/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

推荐阅读