Python requests error "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)"
Python requests error "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)"
我正在使用 API returns 链接和古代文本中的拉丁词示例。我想将响应解析为 JSON 但我收到以下错误:
File "C:\Users\{name}\anaconda3\lib\json\decoder.py", line 355, in
raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 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 个对象的列表。
晚了 post 但这是答案。 API 我正在点击阻止 requests
库使用的默认 user-agent
(请求来自什么类型的设备)。我的解决方案是像这样在请求上手动设置一个 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 认为您是从浏览器中的真实用户而不是机器人发出请求。
我正在使用 API returns 链接和古代文本中的拉丁词示例。我想将响应解析为 JSON 但我收到以下错误:
File "C:\Users\{name}\anaconda3\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 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 个对象的列表。
晚了 post 但这是答案。 API 我正在点击阻止 requests
库使用的默认 user-agent
(请求来自什么类型的设备)。我的解决方案是像这样在请求上手动设置一个 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 认为您是从浏览器中的真实用户而不是机器人发出请求。