随机json.decoder.JSONDecodeError:应为值:第1行第1列(字符0)



我是Python编码的新手,最近学习了API和JSON。我写了一小段测试代码来与随机数生成器交互(https://www.random.org/)。它一直运行得很好,但最近我遇到了一个JSONDecodeError,非常随机和不稳定。这种情况有时会发生,但并非总是发生。我可以运行代码,得到错误,不做任何更改,然后在10分钟后运行代码,不会得到错误。我做了两次检查,以确保API正在通过浏览器运行。以下是基本信息:

编写并运行:
PyCharm Community Edition 2016.3.1
构建#PC-163.9735.8,构建于2016年12月14日
JRE:1.8.0_112-release-408-b6 x86
JVM:OpenJDK Server VM by JetBrains s.r.o

import requests
import json
print("Random Number Generator:")
print("========================")
# RANDOM NUMBER GEN
response01 = requests.get(
"https://www.random.org/integers/?num=1&min=1&max=999999999&col=1&base=10&format=plain&rnd=new")
data1 = response01.json()
print(type(data1))
print(data1)

这段代码只是从API打印一个随机数。这是我得到的随机错误:

Random Number Generator:
========================
Traceback (most recent call last):
File "C:/REDACTED/REDACTED/REDACTED/REDACTED/API Practice 2.py", line 10, in <module>
data1 = response01.json()
File "C:Program Files (x86)Python35-32libsite-packagesrequestsmodels.py", line 850, in json
return complexjson.loads(self.text, **kwargs)
File "C:Program Files (x86)Python35-32libjson__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "C:Program Files (x86)Python35-32libjsondecoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:Program Files (x86)Python35-32libjsondecoder.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)
Process finished with exit code 1

所以我的问题分为两部分
A)这个错误的原因可能是什么
B)为什么它(看起来)是随机发生的?

感谢任何人提供的任何信息。再说一次,我是Python的NOOB,所以请揭露我的无知或缺乏或教育。

注意:REDACTED只是一个占位符。

有时你会遇到HTTP错误,然后响应对象没有内容,所以你无法解析它。

import requests
import json
print("Random Number Generator:")
print("========================")
# RANDOM NUMBER GEN
response01 = requests.get("https://www.random.org/integers/?num=1&min=1&max=999999999&col=1&base=10&format=plain&rnd=new")
try :
data1 = json.loads(response01)
print('[i] Response : %s' % data1)
except JSONDecodeError as e :
print('[!] Error while decoding response contents')
print('[!] %s - %s' % (response01.status_code, response01.text))
# here you could replay the request

相关内容

最新更新