我在Windows上使用Python 3.3。 我想弄清楚如何从雅虎财务下载.csv文件。 这是历史价格文件。
<p> <a href="http://ichart.finance.yahoo.com/table.csv?s=AAPL&d=1&e=1&f=2014&g=d&a=8&b=7&c=1984&ignore=.csv"> <img src="http://img.zgserver.com/windows/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&d=1&e=1&f=2014&g=d&a=8&b=7&c=1984&ignore=.csv" html = urlopen(website) soup = BeautifulSoup(html)
当我运行代码时,我期待它开始下载并将其放到我的下载文件夹中,但是它什么都不做。 它运行,然后停止。 我的下载中没有显示csv文件。 所以我觉得我在这段代码中错过了其他的东西。
使用Windows中的BeautifulSoup4,Chardet和Python 3.3parsing页面时出错
你可以用urllib来做到这一点。 以下代码下载.csv文件并将其内容放入名为“csv”的字符串中。 然后将字符串保存到一个文件中:
from urllib import request # Retrieve the webpage as a string response = request.urlopen("http://ichart.finance.yahoo.com/table.csv?s=AAPL&d=1&e=1&f=2014&g=d&a=8&b=7&c=1984&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 + "n") f.close()
既然你已经使用BeautifulSoup和urllib:
url = BeautifulSoup(html).find('a')['href'] urllib.urlretrieve(url,'/path/to/downloads/file.csv')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。