HTTPS urllib.request,读入JSON

时间:2018-03-14 09:01:03

标签: python

如果我以urlib2

为例
import urllib.request
response = urllib.request.urlopen('http://python.org/')
html = response.read()

然后它运作正常。

我很惊讶地发现我的代码

req = urllib.request.Request('https://www.tehnomanija.rs/it-shop/laptop-racunari')
response = urllib.request.urlopen(req)
the_page = response.read()
data = json.loads(the_page)
print (data)

产生这样的错误

         data = json.loads(the_page)
  File "/home/mm/anaconda3/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/home/mm/anaconda3/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/home/mm/anaconda3/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)

除了其他协议,我不明白为什么这不起作用。

1 个答案:

答案 0 :(得分:3)

json.load()用于从文件加载。您需要json.loads()

data = json.loads(the_page)