需要使用python清理web刮取的数据

2024-09-30 10:42:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图编写一个从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)


Tags: the数据代码importcomhttpurldf
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。这是他们中最慢的

使用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的另一个优点是,您的代码运行速度要快得多

    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])

相关问题 更多 >

    热门问题