【问题标题】:Python 3.6 Downloading .csv files from finance.yahoo.com using requests modulePython 3.6 使用 requests 模块从 Finance.yahoo.com 下载 .csv 文件
【发布时间】:2018-01-31 16:05:54
【问题描述】:

我试图从url 下载一个 .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()

但是当我打开文件 history_of_stock.csv 时,我发现了这个:

    {
        "finance": {
            "error": {
                "code": "Unauthorized",
                "description": "Invalid cookie"
            }
        }
    }
我找不到任何可以解决我的问题的东西。我发现这个线程中有人有同样的问题,除了它在 C# 中:C# Download price data csv file from https instead of http

【问题讨论】:

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


    【解决方案1】:

    为了补充前面的答案并提供具体的完整代码,我编写了一个脚本来完成获取雅虎财经历史股票价格的任务。试着写得尽可能简单。总结一下:当您使用请求获取 URL 时,在许多情况下您无需担心 crumbs 或 cookie。但是,使用雅虎金融,您需要获得面包屑和饼干。一旦你得到饼干,那么你就可以走了!确保为requests.get 调用设置超时。

    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)
    

    【讨论】:

      【解决方案2】:

      确实有一个服务可以解决这个问题,但它是discontinued

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

      还有一篇关于another service 的帖子可能会让您的生活更轻松。

      还有一个 Python module 来解决这个不便,并提供代码来展示如何在没有它的情况下做到这一点。

      【讨论】:

      • 我找不到链接到特定帖子的方法... :(
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 2012-11-12
      • 1970-01-01
      • 2019-01-15
      相关资源
      最近更新 更多