使用 Python 下载 .csv 文件 [英] Download a .csv file with Python

查看:68
本文介绍了使用 Python 下载 .csv 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Windows 上使用 Python 3.3.我想弄清楚如何从雅虎财经下载 .csv 文件.它是历史价格的文件.

I am using Python 3.3 on Windows. I am trying to figure out how to download a .csv file from yahoo finance. It is a file for the Historical Prices.

这是我试图访问链接的源代码.

This is the source code where the link is I'm trying to access.

<p>  
 <a href="http://ichart.finance.yahoo.com/table.csv?s=AAPL&amp;d=1&amp;e=1&amp;f=2014&amp;g=d&amp;a=8&amp;b=7&amp;c=1984&amp;ignore=.csv">
<img src="http://l.yimg.com/a/i/us/fi/02rd/spread.gif" width="16" height="16" alt="" border="0">
<strong>Download to Spreadsheet</strong>
 </a>
</p> 

这是我写的代码.

from urllib.request import urlopen
from bs4 import BeautifulSoup

website = "http://ichart.finance.yahoo.com/table.csv?s=AAPL&amp;d=1&amp;e=1&amp;f=2014&amp;g=d&amp;a=8&amp;b=7&amp;c=1984&amp;ignore=.csv"
html = urlopen(website)
soup = BeautifulSoup(html)

当我运行代码时,我希望它开始下载并将其放入我的下载文件夹中,但它没有做任何事情.它运行然后停止.我的下载中没有显示 csv 文件.所以我想我在这段代码中遗漏了一些东西.

When I ran the code, I was expecting it to start the download and put it into my downloads folder, but it doesn't do anything. It runs and then stops. No csv file shows up in my downloads. So I think I'm missing something else in this code.

推荐答案

您只需使用 urllib 即可完成此操作.以下代码下载 .csv 文件并将内容放入名为csv"的字符串中.然后它将字符串保存到文件中:

You can do this with just urllib. The following code downloads the .csv file and puts the contents into a string named 'csv'. Then it saves the string to a file:

from urllib import request

# Retrieve the webpage as a string
response = request.urlopen("http://ichart.finance.yahoo.com/table.csv?s=AAPL&amp;d=1&amp;e=1&amp;f=2014&amp;g=d&amp;a=8&amp;b=7&amp;c=1984&amp;ignore=.csv")
csv = response.read()

# Save the string to a file
csvstr = str(csv).strip("b'")

lines = csvstr.split("\n")
f = open("historical.csv", "w")
for line in lines:
   f.write(line + "
")
f.close()

这篇关于使用 Python 下载 .csv 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆