【问题标题】:Why do I get an error when i use .json()?为什么我在使用 .json() 时会出错?
【发布时间】:2021-10-02 13:56:39
【问题描述】:

我在使用 .json() 时遇到了一个错误,我在写这篇文章时遵循了一个教程,我很确定我没有改变任何东西,但它不起作用

代码:

import requests
import os #not used
import json #not used
import shutil #not used

header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36"}

url = "https://www.instagram.com/p/CRlNMq5KawJ/"
tail = "?__a=1"
full_url = url + tail

response = requests.get(full_url, headers=header).json()

image_location = response["graphql"]["shortcode_media"]["display_resources"]
image_location = image_location[2].get("src")
print(image_location)

错误:

    Traceback (most recent call last):
  File "C:\Users\3001l\PycharmProjects\Instagram_Bot\Insta_Downloader.py", line 12, in <module>
    response = requests.get(full_url, headers=header).json()
  File "C:\Users\3001l\PycharmProjects\Instagram_Bot\venv\lib\site-packages\requests\models.py", line 910, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\3001l\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\3001l\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\3001l\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Process finished with exit code 1

【问题讨论】:

  • 您是否尝试查看实际返回的响应?
  • 您假设响应中有一个 JSON 值要解码。如果您收到(例如)404 响应而不是 200 响应,则情况并非如此。
  • 没有响应的文字文本(转换为 JSON 之前),这个问题是无法回答的——我们可以做出猜测,但这不是我们在这里为。
  • 我无法使用该 URL 重现错误。可能有防火墙阻止了您,或者 Instagram 阻止了您。如果您发送的请求过多,您可能会超出速率限制。
  • 我们可以通过尝试进行猜测;) Instagram 不喜欢对其进行匿名调用,并对其访问设置了相当严格的限制。如果你打印 response.status_code 我假设你得到 429 这是太多请求错误

标签: python json error-handling python-requests


【解决方案1】:

这可能是因为响应不是 json 本身,或者不是正确的 json 格式。 尝试打印 requests.get(full_url, headers=header)

【讨论】:

  • 一般和错误在这种情况下,他得到一个请求限制错误..
【解决方案2】:

你的标题有一些错误,这些对我来说是有效的。

import requests

headers = {
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:90.0) Gecko/20100101 Firefox/90.0"}

response = requests.get("https://www.instagram.com/p/CRlNMq5KawJ/?__a=1",headers=headers)

if response.status_code != 200:
    print("Some error happened, review response.text")
else:
    content = response.json()

【讨论】:

  • Idk 如果可以,但是我尝试了您的代码,但这对我不起作用,错误仍然在 .json() 部分,即您的情况的最后一行。也试过用另一台电脑
  • 你得到 status_code == 200?还是不行?
  • 没错,我用你的用户代理和我的用户代理都试过了,但状态码总是 200,我在 pycharm 和在线解释器上试过,同样的事情。
  • response.text的内容是什么
  • 我无法复制所有文字,请查看here
猜你喜欢
  • 2021-03-04
  • 2010-10-18
  • 1970-01-01
  • 2022-01-21
  • 2021-09-10
  • 2019-01-14
  • 2018-12-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多