我已经实现了这个答案给出的功能:https://quant.stackexchange.com/a/70155/33457
当我运行此代码时,有时它运行良好,但大多数时候它会返回此错误:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
有趣的是,它是否经历或返回这个错误似乎是完全随机的?这是为什么?
我试图找出我的
headers
是否有问题,但我不知道
在这里查看我的完整代码;
import requests
def get_symbol_for_isin(isin):
url = 'https://query1.finance.yahoo.com/v1/finance/search'
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.109 Safari/537.36',
}
params = dict(
q=isin,
quotesCount=1,
newsCount=0,
listsCount=0,
quotesQueryId='tss_match_phrase_query'
)
resp = requests.get(url=url, headers=headers, params=params)
data = resp.json()
if 'quotes' in data and len(data['quotes']) > 0:
return data['quotes'][0]['symbol']
else:
return None
apple_isin = 'US0378331005'
print(get_symbol_for_isin(apple_isin))
返回应为“AAPL”
您应该检查回复的
status_code
。如果服务器返回 4xx 错误,它可能不是 JSON。
def get_symbol_for_isin(isin):
url = 'https://query1.finance.yahoo.com/v1/finance/search'
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.109 Safari/537.36',
}
params = dict(
q=isin,
quotesCount=1,
newsCount=0,
listsCount=0,
quotesQueryId='tss_match_phrase_query'
)
resp = requests.get(url=url, headers=headers, params=params)
if resp.status_code != 200:
return resp.reason
data = resp.json()
if 'quotes' in data and len(data['quotes']) > 0:
return data['quotes'][0]['symbol']
else:
return None