Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Python 3.6使用请求模块从finance.yahoo.com下载.csv文件_Python 3.x_Csv_Python Requests - Fatal编程技术网

Python 3.x Python 3.6使用请求模块从finance.yahoo.com下载.csv文件

Python 3.x Python 3.6使用请求模块从finance.yahoo.com下载.csv文件,python-3.x,csv,python-requests,Python 3.x,Csv,Python Requests,我试图从这里下载一个股票历史的.csv文件。这是我的密码: import requests r = requests.get("https://query1.finance.yahoo.com/v7/finance/download/CHOLAFIN.BO?period1=1514562437&period2=1517240837&interval=1d&events=history&crumb=JaCfCutLNr7") file = open(r"history_of

我试图从这里下载一个股票历史的.csv文件。这是我的密码:

    import requests
    r = requests.get("https://query1.finance.yahoo.com/v7/finance/download/CHOLAFIN.BO?period1=1514562437&period2=1517240837&interval=1d&events=history&crumb=JaCfCutLNr7")
    file = open(r"history_of_stock.csv", 'w')
    file.write(r.text)
    file.close()
但当我打开_stock.csv的文件history_时,我发现:
    {
        "finance": {
            "error": {
                "code": "Unauthorized",
                "description": "Invalid cookie"
            }
        }
    }

我找不到任何可以解决我问题的东西。我发现这个线程中有人有同样的问题,只是它在C中:

有一个服务正是为了这个,但它是

现在你可以做你想做的,但首先你需要得到一块饼干。这里有一个如何做的例子。 基本上,首先您需要发出一个无用的请求来获取Cookie,然后,有了这个Cookie,您可以查询您实际需要的任何其他内容

还有一个帖子可能会让你的生活更轻松


还有一个Python解决了这个问题,并编写了代码来演示如何在没有它的情况下做到这一点。

为了补充前面的答案并提供一个具体完整的代码,我编写了一个脚本,完成了在Yahoo Finance中获取历史股价的任务。试着写得尽可能简单。总结一下:当您使用请求获取URL时,在许多情况下,您不需要担心面包屑或饼干。然而,有了雅虎金融,你需要得到面包屑和饼干。一旦你拿到饼干,你就可以走了!确保在
请求上设置超时。获取
调用

import re
import requests
import sys
from pdb import set_trace as pb

symbol = sys.argv[-1]
start_date = '1442203200' # start date timestamp
end_date   = '1531800000' # end date timestamp

crumble_link = 'https://finance.yahoo.com/quote/{0}/history?p={0}'
crumble_regex = r'CrumbStore":{"crumb":"(.*?)"}'
cookie_regex = r'set-cookie: (.*?);'
quote_link = 'https://query1.finance.yahoo.com/v7/finance/download/{}?period1={}&period2={}&interval=1d&events=history&crumb={}'

link = crumble_link.format(symbol)
session = requests.Session()
response = session.get(link)

# get crumbs

text = str(response.content)
match = re.search(crumble_regex, text)
crumbs = match.group(1)

# get cookie

cookie = session.cookies.get_dict()

url = "https://query1.finance.yahoo.com/v7/finance/download/%s?period1=%s&period2=%s&interval=1d&events=history&crumb=%s" % (symbol, start_date, end_date, crumbs)

r = requests.get(url,cookies=session.cookies.get_dict(),timeout=5, stream=True)

out = r.text

filename = '{}.csv'.format(symbol)

with open(filename,'w') as f:
    f.write(out)

我找不到链接到特定帖子的方法…:(