[英]Getting website data from a URL using requests
尝试使用请求来检索网站数据并将其转换为 json 文件。 虽然它适用于您将在下面看到的一个网址,但它不适用于其他类型的网址。 我确定它只是一个错误的网址,但我认为我的语法也有问题。
r = requests.get('https://icanhazdadjoke.com/', headers={'Accept': 'application/json'})
data = r.json()
data
output: {'id': 'Z8UDIRuXLmb',
'joke': 'Who did the wizard marry? His ghoul-friend',
'status': 200}
但是当我尝试:
r = requests.get('https://icanhazdadjoke.com/', headers={'Accept': 'application/json'})
data = r.json()
print(data)
or
data = requests.get('http://web.archive.org/web/20180326124748/https://www.theguardian.com/side-hustle', headers={'Accept': 'application/json'}).json()
print(data)
我得到这个完整的回溯错误:
---------------------------------------------------------------------------
JSONDecodeError Traceback (most recent call last)
<ipython-input-50-92f4c7755f72> in <module>()
----> 1 data = requests.get('http://web.archive.org/web/20180326124748/https://www.theguardian.com/side-hustle', headers={'Accept': 'application/json'}).json()
2 data
3 frames
/usr/local/lib/python3.6/dist-packages/requests/models.py in json(self, **kwargs)
896 # used.
897 pass
--> 898 return complexjson.loads(self.text, **kwargs)
899
900 @property
/usr/lib/python3.6/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
352 parse_int is None and parse_float is None and
353 parse_constant is None and object_pairs_hook is None and not kw):
--> 354 return _default_decoder.decode(s)
355 if cls is None:
356 cls = JSONDecoder
/usr/lib/python3.6/json/decoder.py in decode(self, s, _w)
337
338 """
--> 339 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
340 end = _w(s, end).end()
341 if end != len(s):
/usr/lib/python3.6/json/decoder.py in raw_decode(self, s, idx)
355 obj, end = self.scan_once(s, idx)
356 except StopIteration as err:
--> 357 raise JSONDecodeError("Expecting value", s, err.value) from None
358 return obj, end
JSONDecodeError: Expecting value: line 2 column 1 (char 1)
这只是一个错误的网址吗? 谢谢!
问题不在于您的 Python 代码。
您可以使用 Linux 中的 wget cli 程序进行检查。
和
wget https://icanhazdadjoke.com
你得到那个网页的 HTML 代码,但是
wget --header="Accept:application/json" https://icanhazdadjoke.com
你会得到一个 JSON 数据,其中包含一个类似于你所展示的笑话。
但是,对于您收到错误的网站,即使使用--header="Accept:application/json"
,您--header="Accept:application/json"
得到 HTML 代码而不是 JSON 代码。 因此,尝试将返回的数据解码为 JSON 会产生错误,因为它不是 JSON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.