【问题标题】:Need to clean web scraped data using python需要使用 python 清理网络抓取的数据
【发布时间】:2020-10-03 16:42:25
【问题描述】:

我正在尝试编写用于从http://goldpricez.com/gold/history/lkr/years-3 抓取数据的代码。我写的代码如下。该代码有效,并给了我预期的结果。

import pandas as pd

url = "http://goldpricez.com/gold/history/lkr/years-3"

df = pd.read_html(url)

print(df)

但结果是一些不需要的数据,我只想要表中的数据。请帮我解决这个问题。

Here I have added the image of the output with unwanted data (red circled)

【问题讨论】:

  • 您可以随时对数据框进行切片以删除不需要的数据。或者,在使用 pandas 库之前使用 Beautiful soup 库解析 html。
  • read_html返回HTML源中每个表格的数据框列表,使用列表索引访问所需的数据框stackoverflow.com/questions/39710903/…
  • 您使用pd.read_html 是正确的。只需选择数据所在的正确索引 [3]。请参阅下面的答案

标签: python web-scraping


【解决方案1】:
    import pandas as pd



   url = "http://goldpricez.com/gold/history/lkr/years-3"

   df = pd.read_html(url)# this will give you a list of dataframes from html

  print(df[3])

【讨论】:

  • 谢谢伙计。它工作正常和小问题。 df[3] 是做什么的??
  • 使用urllib.requests 实际上只是执行了两次该过程,而.read_html 这样做了:) 所以不需要该步骤
  • 为什么我投反对票的解释:我很少投反对票。我通常不喜欢在不解释我可以改进的地方投反对票。所以这里是我的。您添加了额外的和未使用的代码from urllib.request import urlopen, Request url = "http://goldpricez.com/gold/history/lkr/years-3" req = Request(url=url) html = urlopen(req).read() 所有这些都没有使用。如果所有内容都被删除,df[3] 将起作用。 ;) 因此。希望你明白:)
  • @ThejithaAnjana df[3] 打印数据帧列表中的第四个数据帧。
【解决方案2】:

为此使用 BeautifulSoup,下面的代码可以完美运行

import requests
from bs4 import BeautifulSoup
url = "http://goldpricez.com/gold/history/lkr/years-3"
r = requests.get(url)
s = BeautifulSoup(r.text, "html.parser")
data = s.find_all("td")
data = data[11:]
for i in range(0, len(data), 2):
    print(data[i].text.strip(), "      ", data[i+1].text.strip())

使用 BeautifulSoup 的另一个优点是它比您的代码更快

【讨论】:

  • .read_html 在后台使用 bs4 ;) flavor : str or None, container of strings The parsing engine to use. ‘bs4’ and ‘html5lib’ are synonymous with each other, they are both there for backwards compatibility. The default of None tries to use lxml to parse and if that fails it falls back on bs4 + html5lib.
【解决方案3】:

您使用.read_html 的方式将返回所有表的列表。您的表位于索引 3

import pandas as pd

url = "http://goldpricez.com/gold/history/lkr/years-3"

df = pd.read_html(url)[3]

print(df)

.read_html 调用 URL,并在后台使用 BeautifulSoup 解析响应。您可以像在.read_csv 中那样更改解析、表的名称、传递标头。更多详情请查看.read_html

为了速度,您可以使用lxml,例如pd.read_html(url, flavor='lxml')[3]。默认情况下,使用第二慢的html5lib。另一种口味是html.parser。它是所有这些中最慢的。

【讨论】:

    猜你喜欢
    • 2018-06-30
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 2018-03-13
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    相关资源
    最近更新 更多