首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python错误"json.decoder.JSONDecodeError:期待值:第1行第1列(char 0)“

Python错误"json.decoder.JSONDecodeError:期待值:第1行第1列(char 0)“
EN

Stack Overflow用户
提问于 2021-12-18 19:54:19
回答 1查看 385关注 0票数 0

我正在使用一个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)

这是我的代码:

代码语言:javascript
复制
    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对象列表。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-12 01:03:45

一篇迟来的文章,但答案是这样的。API命中的API阻塞了requests库使用的默认requests(请求来自何种类型的设备)。我的解决方案是在请求中手动设置一个user-agent字段,如下所示:

代码语言:javascript
复制
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认为您是从浏览器中的实际用户那里请求的,而不是机器人。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70406639

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档