Requests: json() 使用 JSONDecodeError 使解释器崩溃

创建于 2017-09-13  ·  3评论  ·  资料来源: psf/requests

我在请求 v. 2.18.4 和 2.14.2 以及 Python 3.6.1 和 3.6.2 中复制了这个。 我使用了系统安装的 Python/requests(从 python.org 下载的带有 Python 3.6.1 的 macOS Sierra),作为 conda 4.3.25 的一部分安装的 Python/requests,以及从 conda-forge 安装的最新 Python 和 requests。

到处都是一样的结果。

预期结果

预计会看到 JSON 值字典,如下所示: http :

实际结果

Python 解释器崩溃。

繁殖步骤

Python 3.6.2 | packaged by conda-forge | (default, Jul 23 2017, 23:01:38) 
[GCC 4.2.1 Compatible Apple LLVM 6.1.0 (clang-602.0.53)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> r = requests.get('https://pypi.python.org/pypi')
>>> r.status_code
200
>>> r.encoding
'utf-8'
>>> r.json()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/psimpson/miniconda3/envs/test/lib/python3.6/site-packages/requests/models.py", line 892, in json
    return complexjson.loads(self.text, **kwargs)
  File "/Users/psimpson/miniconda3/envs/test/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/Users/psimpson/miniconda3/envs/test/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Users/psimpson/miniconda3/envs/test/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

系统信息

$ python -m requests.help
{
  "chardet": {
    "version": "3.0.4"
  },
  "cryptography": {
    "version": "2.0.3"
  },
  "idna": {
    "version": ""
  },
  "implementation": {
    "name": "CPython",
    "version": "3.6.2"
  },
  "platform": {
    "release": "16.7.0",
    "system": "Darwin"
  },
  "pyOpenSSL": {
    "openssl_version": "100020cf",
    "version": "17.2.0"
  },
  "requests": {
    "version": "2.18.4"
  },
  "system_ssl": {
    "version": "100020cf"
  },
  "urllib3": {
    "version": "1.22"
  },
  "using_pyopenssl": true
}

最有用的评论

@justlurking ,这实际上按预期工作。 .json() 方法仅可用于 json 格式的响应内容。 您请求的网页正在返回 HTML 文档,因此无法正常工作。

您需要修改 Accept 标头并尝试检索有效的 json 数据,或者添加代码来处理 json 数据不可用的情况。 我正在关闭它,因为事情按预期工作。

所有3条评论

@justlurking ,这实际上按预期工作。 .json() 方法仅可用于 json 格式的响应内容。 您请求的网页正在返回 HTML 文档,因此无法正常工作。

您需要修改 Accept 标头并尝试检索有效的 json 数据,或者添加代码来处理 json 数据不可用的情况。 我正在关闭它,因为事情按预期工作。

感谢您的超级快速和信息丰富的回复,并为浪费您的时间道歉。 考虑到我测试了多个版本并且在 GitHub 上没有强烈抗议,我应该意识到它可能是这样的。 🤦

我想最好的办法是导入 json.JSONDecodeError 并做这样的事情?

try:
    r.json()
except JSONDecodeError as e:
    <handle exception>

所以这实际上应该是 ValueError 的一个子类,所以我认为如果您不想导入,您将能够捕捉到它。 这取决于您想要的特异性水平。

不过,这个总体思路是我建议的方法。 希望有帮助!

此页面是否有帮助?
0 / 5 - 0 等级