雅虎财经 V7 API 现在需要 cookie?(Python)

Jus*_*tin 7 python cookies yahoo-finance python-requests

url = 'https://query2.finance.yahoo.com/v7/finance/quote?symbols=TSLA&fields=regularMarketPreviousClose&region=US&lang=en-US'
headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'
}
data = requests.get(url,headers=headers)
prepost_data = data.json()
Run Code Online (Sandbox Code Playgroud)

最近,雅虎财经似乎更改了他们的 V7 API,要求每个请求都需要 cookie。运行上面的代码,我收到 Invalid Crumb 错误

{"finance":{"result":null,"error":{"code":"Unauthorized","description":"Invalid Crumb"}}}

这个问题似乎在这个 Github 存储库中也已知:https://github.com/joshuaulrich/quantmod/issues/382

他们似乎有一个有效的补丁:https ://github.com/joshuaulrich/quantmod/pull/383/commits

但代码都是用 R 编写的...有人知道如何将其翻译成 Python 吗?

mah*_*dar 14

这对我有用。

  1. 对 URL https://fc.yahoo.com进行 HTTP GET 调用。虽然此调用会导致 404 错误,但我们只需要它set-cookie从响应标头中提取出来,然后在后续调用中使用
  2. 现在,通过包含从之前的响应标头中获取的 cookie,对 URL https://query2.finance.yahoo.com/v1/test/getcrumb进行 HTTP GET 调用。此调用将检索碎屑值。
  3. 替换[crumb-value]以下 URL 并使用 cookie 进行 HTTP GET 调用https://query2.finance.yahoo.com/v7/finance/quote?symbols=TSLA&crumb=[crumb-value]
  4. 缓存 cookie 值和 crumb 值以跳过前两个步骤