简体   繁体   English

Yahoo finance API 在旧的 URL 和 User-Agent 上给出错误 403(禁止)

[英]Yahoo finance API gives error 403 (forbidden) on old URL and User-Agent

One of the use cases I use Yahoo finance API for is to find out the earnings date for a given stock.我使用 Yahoo finance API 的一个用例是找出给定股票的收益日期。 This was working fine till about 7/2021 but started giving error 403 (forbidden).这在 7/2021 之前一直运行良好,但开始出现错误 403(禁止)。

After struggling a while, found that adding a {'User-agent': 'Mozilla/5.0'} header would fix the issue.经过一段时间的努力,发现添加{'User-agent': 'Mozilla/5.0'} header 可以解决问题。 If you face a similar issue, you could try and see if it fixes for you too.如果您遇到类似的问题,您可以尝试看看它是否也能解决您的问题。 Here is a sample screenshot:这是一个示例屏幕截图:

>>> url="https://query2.finance.yahoo.com/v10/finance/quoteSummary/PYPL?modules=calendarEvents"
>>> r=requests.get(url)
>>> r
<Response [403]>
>>> r=requests.get(url, headers={'User-agent': 'Mozilla/5.0'})
>>> r
<Response [200]>
>>> r.json()
{'quoteSummary': {'result': [{'calendarEvents': {'maxAge': 1, 'earnings': {'earningsDate': [{'raw': 1635764340, 'fmt': '2021-11-01'}, {'raw': 1636113600, 'fmt': '2021-11-05'}], 'earningsAverage': {'raw': 1.13, 'fmt': '1.13'}, 'earningsLow': {'raw': 0.97, 'fmt': '0.97'}, 'earningsHigh': {'raw': 1.27, 'fmt': '1.27'}, 'revenueAverage': {'raw': 6265160000, 'fmt': '6.27B', 'longFmt': '6,265,160,000'}, 'revenueLow': {'raw': 6041000000, 'fmt': '6.04B', 'longFmt': '6,041,000,000'}, 'revenueHigh': {'raw': 6539200000, 'fmt': '6.54B', 'longFmt': '6,539,200,000'}}, 'exDividendDate': {}, 'dividendDate': {}}}], 'error': None}}

I was facing a similar problem.我遇到了类似的问题。 Apparently two things have changed:显然有两件事发生了变化:

  1. they updated the URL他们更新了 URL
  2. they limit particular user agents (Matlab is explicitly rejected)他们限制特定的用户代理(明确拒绝 Matlab)

The URL as of 6/16/2021 is:截至 2021 年 6 月 16 日的 URL 是:

symbolString = 'TGT'; % look up Target prices as an example  
urlBase = 'https://query1.finance.yahoo.com/v7/finance/download/'; % base as of   6/16/2021
url = [urlBase,symbolString];  

Then we explicitly set the user agent:然后我们显式设置用户代理:

options = weboptions('UserAgent',''); # as of 6/16/2021 it is enough to submit a blank user agent

you need to update your python package in your env:您需要在您的环境中更新您的 python package:

pip install yahoo-fin -U

This worked 14-Jan-2022.这在 2022 年 1 月 14 日有效。 I Googled "what is my user agent" to get a user agent string.我用谷歌搜索“什么是我的用户代理”来获取用户代理字符串。

import requests
url='https://query1.finance.yahoo.com/v7/finance/download/TSLA'
headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'
}
r = requests.get(url, headers=headers)
print(r.status_code)
print(r.content)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM