Python url 不下载文件



我正在开发一个量化交易应用程序,从雅虎财经获取财务信息。代码如下。

from datetime import datetime
from calendar import timegm
import time
def constructYFURL(ticker, start_date,end_date,freq):
start_date = str(timegm(time.strptime(start_date, "%Y-%m-%d")))
end_date = str(timegm(time.strptime(end_date, "%Y-%m-%d")))
if freq == 'w':
interval = '1wk'
else:
interval = '1mo'
if freq == 'd':
interval = '1d'
yFURL = "https://query1.finance.yahoo.com/v7/finance/download/"+ticker+"?      period1="+start_date+"&period2="+end_date+"&interval="+interval+"&events=history&crumb=jfsRogYbS3."
return yFURL

def download(filePath, urlOfFile):
import urllib2
webRequest = urllib2.Request(urlOfFile)
try:
page = urllib2.urlopen(webRequest)
content = page.read()
with open(filePath, 'wb') as output:
output.write(bytearray(content))
except urllib2.HTTPError, e:
print e.fp.read()

在下面,我通过选择我想要股票报价的股票代码和时间段来测试代码。

from download import constructYFURL, download
from datetime import datetime
from time import time
ticker = "NFLX"
start_date = "2016-07-18"
end_date = "2017-08-18"
freq = "d"
yFURL = constructYFURL(ticker, start_date,end_date,freq)
print yFURL
localFilePath = "/Users/Gebruiker/pytest/nflx.csv"
download(localFilePath,yFURL)

这是生成的网址:

https://query1.finance.yahoo.com/v7/finance/download/NFLX?period1=1468800000&period2=1503014400&interval=1d&events=history&crumb=eVjSxKy2scr

错误给出如下:

{
"finance": {
"error": {
"code": "Unauthorized",
"description": "Invalid cookie"
}
}
}
Process finished with exit code 0

使用我的浏览器单击链接时,它确实会下载文件,但是,仍然给我错误,并且我在指定的要保存的存储库中找不到csv文件。有人可以帮助我吗?我认为通过使用处理 cookie 的 urllib2 python 库中的处理程序,我可以解决这个问题,但我不知道如何。

您可能需要登录才能访问该 URL。

在这种情况下,您需要在请求的标头中包含 Cookie,这些 cookie 会在您登录时为您生成。它可以在您的浏览器中工作,因为您的浏览器会为您处理它。

一种方法是使用requests模块及其Session对象,该对象会自动管理 cookie。创建一个Session,从它登录,然后你应该能够使用它来访问你的URL。

最新更新