将抓取的数据加载到列表中

时间:2018-09-18 16:57:56

标签: python-3.x beautifulsoup python-requests

我能够成功地从网站上抓取一些文本,现在我正尝试将文本加载到列表中,以便以后将其转换为Pandas DataFrame。

该网站以scsv格式提供了数据,因此可以快速获取。

以下是我的代码:

import requests
from bs4 import BeautifulSoup

#Specify the url:url
url = "http://rotoguru1.com/cgi-bin/fyday.pl?week=1&year=2017&game=dk&scsv=1"

# Packages the request, send the request and catch the response: r
r = requests.get(url)

#Extract the response:html_doc
html_doc = r.text


soup = BeautifulSoup(html_doc,"html.parser")

#Find the tags associated with the data you need, in this case
# it's the "pre" tags


for data in soup.find_all("pre"):
    print(data.text)

样本输出

  

周;年; GID;名称;职位;团队; h / a; Oppt; DK点数; DK薪水   1; 2017; 1254; Smith,Alex; QB; kan; a; nwe; 34.02; 5400 1; 2017; 1344; Bradford,   Sam; QB; min; h; nor; 28.54; 5900

2 个答案:

答案 0 :(得分:0)

这是您可以做的一件事,尽管有可能比我更了解熊猫的人可以提供一些更好的建议。

您有r.text。将其放入方便的文本文件中,我称之为temp.csv。现在,您可以使用pandas read_csv方法将这些数据放入数据框中。

>>> df = pandas.read_csv('temp.csv', sep=';')

附录:

假设results像这样。

>>> results = [['a', 'b', 'c'], [1,2,3], [4,5,6]]

然后您可以通过这种方式将它们放在数据框中。

>>> df = pandas.DataFrame(results[1:], columns=results[0])
>>> df
   a  b  c
0  1  2  3
1  4  5  6

答案 1 :(得分:0)

使用打开功能写入csv文件

import requests
from bs4 import BeautifulSoup
url = "http://rotoguru1.com/cgi-bin/fyday.pl?week=1&year=2017&game=dk&scsv=1"
r = requests.get(url)
html_doc = r.content
soup = BeautifulSoup(html_doc,"html.parser")
file = open(“data.csv”,”w”)
for data in soup.find("pre").text.split('\n'):
    file.write(data.replace(';',','))
file.close()
相关问题