【问题标题】:Python - Requests - JSONDecodeErrorPython - 请求 - JSONDecodeError
【发布时间】:2021-03-31 10:32:32
【问题描述】:

你好, 在 Python 中运行以下脚本时出现以下错误:

import requests

r = requests.get('https://www.instagram.com/p/CJDxE7Yp5Oj/?__a=1')
data = r.json()['graphql']['shortcode_media']

C:\ProgramData\Anaconda3\envs\test\python.exe C:/Users/Solba/PycharmProjects/test/main.py
回溯(最近一次通话最后一次):
文件“C:/Users/Solba/PycharmProjects/test/main.py”,第 4 行,在
数据 = r.json()
文件“C:\ProgramData\Anaconda3\envs\test\lib\site-packages\requests\models.py”,第 900 行,在 json
返回 complexjson.loads(self.text, **kwargs)
文件“C:\ProgramData\Anaconda3\envs\test\lib\json_init_.py”,第 357 行,加载中
返回 _default_decoder.decode(s)
文件“C:\ProgramData\Anaconda3\envs\test\lib\json\decoder.py”,第 337 行,在 decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
文件“C:\ProgramData\Anaconda3\envs\test\lib\json\decoder.py”,第 355 行,在 raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError:预期值:第 1 行第 1 列(字符 0)

进程以退出代码 1 结束


Python 版本:3.9
PyCharm 版本:2020.3.1
蟒蛇版本:1.10.0


请帮忙。谢谢你。

【问题讨论】:

标签: python python-requests python-jsons


【解决方案1】:

r.json() 期望 API 返回一个 JSON 字符串。 API 应该明确说明它通过响应标头使用 JSON 进行响应。

在这种情况下,您请求的 URL 要么未使用正确的 JSON 响应,要么未明确表示它使用 JSON 响应。

您可以先通过以下方式检查 URL 发送的响应:

data = r.text
print(data)

如果响应可以被视为 JSON 字符串,那么您可以使用:

import json
data = json.loads(r.text)

注意: 您还可以检查 content-typeAccept 标头以确保请求和响应属于所需的数据类型

【讨论】:

    【解决方案2】:

    原因是响应返回的不是 JSON,而是整个 HTML 页面。尝试r.text 而不是r.json()...,然后从那里做任何你想做的事情。

    如果您不确定它返回的内容类型:

    h = requests.head('https://www.instagram.com/p/CJDxE7Yp5Oj/?__a=1')
    header = h.headers
    contentType = header.get('content-type')
    print(contentType)
    

    根据您的 URL,它返回 text/html

    或者,您可以尝试在请求中添加User-Agent - 这是为了模拟请求,使其看起来像是来自浏览器,而不是脚本。

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/46.0.2490.80'
    }
    
    r = requests.get('https://www.instagram.com/p/CJDxE7Yp5Oj/?__a=1', headers=headers)
    data = r.json()
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-19
    • 2023-02-04
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2021-05-06
    • 2021-12-09
    • 2019-04-02
    相关资源
    最近更新 更多