使用请求从URL获取网站数据

时间:2020-09-22 18:18:04

标签: python json python-requests

尝试使用请求来检索网站数据并将其转换为json文件。虽然它适用于一个网址,但您将在下面看到它,但不适用于其他类型的网址。我确定它只是一个错误的URL,但我认为我的语法也已关闭。

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)

这只是一个错误的网址吗?谢谢!

1 个答案:

答案 0 :(得分:0)

问题不在您的Python代码中。

您可以使用Linux中的wget cli程序进行检查。

使用

wget https://icanhazdadjoke.com

您获得了该网页的HTML代码,但是使用了

wget --header="Accept:application/json" https://icanhazdadjoke.com

您获得的JSON数据包含一个与所显示的笑话相似的笑话。

但是,对于该网站,即使使用--header="Accept:application/json",也会收到HTML代码而不是JSON代码。因此,尝试将返回的数据解码为JSON会产生错误,因为它不是JSON。