首页 > 解决方案 > 从 html 中清理数据

问题描述

我正在尝试清理通过网络抓取提取的一部分数据。包含数据的 HTML 代码如下:

<li class="price-was">
    $1,699.00
    <span class="price-was-data" style="display: none">1699.00</span>
</li>

要提取数据,我使用以下代码行:

price_products_before = product.findAll("li",{"class":"price-was"})
PriceBefore = price_products_before[0].text

我使用它是因为数据如下:

'\r\n       $1,699.00\r\n            1699.00\n'

使用以下代码行,我设法以某种方式对其进行了清理,但我仍然有两倍的数字。

PriceBefore = price_products_before[0].text.strip().replace("\r\n","")

我只需要一次 1699 没有任何空格 \r 或 \n。

标签: htmlpython-3.xweb-scrapingbeautifulsoupdata-cleaning

解决方案


from bs4 import BeautifulSoup

html = """<li class="price-was">
    $1,699.00
    <span class="price-was-data" style="display: none">1699.00</span>
</li>"""

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

try:
    print(soup.find("li", class_="price-was").next_element.strip())
except:
    print("Not Found")

输出:

$1,699.00

推荐阅读