【问题标题】:Cleaning data from html从 html 中清理数据
【发布时间】:2020-07-03 02:29:38
【问题描述】:

我正在尝试清理通过网络抓取提取的部分数据。包含数据的 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。

【问题讨论】:

  • 你的意思是这样? PriceBefore = price_products_before[0].text.split()
  • 对不起,如果您需要 1699.00,请从 span 而不是 LI 中获取它
  • price_products_before = product.findAll("span",{"class":"price-was-data"}) PriceBefore = price_products_before[0].text
  • 不起作用... IndexError Traceback(最近一次调用最后一次) in 40 #Preu anterior 41 preu_productes_abans = producte.findAll("span" ,{"class":"price-was-data"}) ---> 42 PreusAbans = preu_productes_abans[0].text 43 IndexError: list index out of range
  • 或许与显示无关?

标签: html python-3.x web-scraping beautifulsoup data-cleaning


【解决方案1】:
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

【讨论】:

  • 如何将其存储在变量中?我需要将其导出为 .csv
  • 你能帮帮我吗?
  • 你是对的!我太傻了!太感谢了!明白了;)
猜你喜欢
  • 2011-04-11
  • 2019-11-22
  • 1970-01-01
  • 2021-04-18
  • 1970-01-01
  • 2020-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多