【发布时间】:2021-07-15 03:40:36
【问题描述】:
我正在尝试从 Python 的请求模块调用 API。在邮递员上,返回的响应标头中的 Content-Type 是application/json; charset=utf-8,响应 json 数据是我期望的样子。但是,在 python 上的 API 的 get 方法之后运行 response.json() 会引发错误 simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)。
希望有人能帮助解释为什么会发生这种情况。
Postman 返回内容的前几行:
{
"Pagination": {
"query": "",
"index": "PRODUCTION_PG_FEATURED_DESC",
"limit": "100",
"page": 1,
"total": 8556,
"lastPage": "/api/v3/browse?_tags=adidas&page=10&productCategory=sneakers&resultsPerPage=100",
"sort": [
"featured"
],
"order": [
"DESC"
],
"currentPage": "/api/v3/browse?_tags=adidas&page=1&productCategory=sneakers&resultsPerPage=100",
"nextPage": "/api/v3/browse?_tags=adidas&page=2&productCategory=sneakers&resultsPerPage=100",
"previousPage": null
},
我的代码块:
import requests
productsAPI = 'https://stockx.com/api/browse?_tags=nike&productCategory=sneakers&page=1&resultsPerPage=100'
headers = {"accept": "*/*", "accept-language": "en-US,en;q=0.9", "accept-encoding" : "gzip, deflate, br","User-Agent" :"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36",
"Connection" : "keep-alive"}
response = requests.get(productsAPI, headers = headers)
print(response.text)
if response.status_code != 200:
print(response.status_code)
try:
data = response.json()
except:
print('fail')
print(data["Facets"]["brand"])
【问题讨论】:
-
你能显示响应的内容是什么吗?
-
Edit 您的问题非常简单。不要将代码/数据放入 cmets。
-
以上 json 有效(缺少关闭
})。如果response.json()报错,您可以在这里粘贴response.text进行分析。 -
您说的是“邮递员”,响应是您所期望的,但错误在于
request模块的使用,但尚未提供response对象的确切状态。请提供来自response对象的相关字段的输出(例如print(response.text)或其标头),而不仅仅是邮递员提供的预期输出。 -
向我们展示您的代码。很容易犯你眼睛看不到的愚蠢错误。
标签: python json python-requests