【问题标题】:JSON Decode Error when requesting JSON response from Google从 Google 请求 JSON 响应时出现 JSON 解码错误
【发布时间】:2020-08-31 19:43:54
【问题描述】:

我正在尝试理解 requests python 包

import requests

url = "https://www.google.com/search?q=london"

response = requests.get(url, headers={"Accept": "application/json"})

data = response.json()

我收到以下错误: json.decoder.JSONDecodeError:预期值:第 1 行第 1 列(字符 0)

但是,此代码确实适用于其他一些网站。这是否有原因在特定网站上会出错?有没有办法解决它?例如,如果我在 Google 上搜索伦敦时想要搜索结果?

谢谢

【问题讨论】:

    标签: python web-scraping python-requests


    【解决方案1】:

    response.json() 不会将任何服务器响应转换为 JSON,它只是解析“字符串化”的 JSON。所以如果服务器返回一个不是 JSON 的字符串,那么这将抛出一个解码错误。

    有些服务器确实会返回 JSON 对象,在这种情况下,您的代码会起作用。在https://www.google.com/search?q=london 的情况下,这实际上返回了 HTML 代码(正如您所期望的,因为它是一个网页)。

    您可以通过打印响应来测试:

    print(response.text)
    

    哪个输出:

    # some very long output that ends with:
    ...();})();google.drty&&google.drty();</script></body></html>
    

    注意到末尾的&lt;/html&gt; 标签了吗?所以这不能被解析成 JSON。

    那么如何将其解析为可用的 HTML?你可以用漂亮的汤:

    import requests
    from bs4 import BeautifulSoup
    
    url = "https://www.google.com/search?q=london"
    
    response = requests.get(url, headers={"Accept": "application/json"})
    
    soup = BeautifulSoup(response.text)
    
    print(soup.prettify())
    

    【讨论】:

    • 谢谢,这是有道理的,但是在使用修复程序运行它时出现以下错误:AttributeError: 'Response' object has no attribute 'data'
    • 糟糕,我的意思是response.text。修复了。