我正在使用一个API,它返回古代文本中拉丁语单词的链接和示例。我想将响应解析为JSON,但是我收到了以下错误:
"C:\Users{name}\anaconda3\lib\json\decoder.py",文件
第355行,在raw_decode中,从None json.decoder.JSONDecodeError中提出JSONDecodeError(“预期值”,s,err.value):Expecting值:第1列(char 0)
这是我的代码:
def get_concordance(self, word):
data = requests.get(f"https://latin.packhum.org/rst/concordance/{word}?authmax=3&max=10000000")
print(data.content)
data = data.json()
return data在打印data.content时,它似乎是HTML而不是JSON,但是,如果您访问{word}字段中带有拉丁单词的URL,它将显示一个JSON对象列表。
发布于 2022-03-12 01:03:45
一篇迟来的文章,但答案是这样的。API命中的API阻塞了requests库使用的默认requests(请求来自何种类型的设备)。我的解决方案是在请求中手动设置一个user-agent字段,如下所示:
def get_concordance(word):
url = f"https://latin.packhum.org/rst/concordance/{word}?authmax=3&max=10"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36"}
requests.get(url, headers=headers)这使API认为您是从浏览器中的实际用户那里请求的,而不是机器人。
https://stackoverflow.com/questions/70406639
复制相似问题