【问题标题】:Python http request not returning json outputPython http请求不返回json输出
【发布时间】:2020-08-07 08:32:48
【问题描述】:

当我使用以下命令时,我会从 url 获得正确的 json 响应: curl --user user:password -H Accept:application/json -H Content-Type:application/json -X GET <url>

“正文”:{ “项目”: [ {........}]}

但是,当我尝试使用 python 请求模块做同样的事情时

import requests

from requests.packages.urllib3.exceptions import InsecureRequestWarning

requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

user='admin'
password='yanQE3B'
url=<requestUrl>

response = requests.get(url, auth=(user, password) , verify=False)

print ( response.content )  ## prints html content

print ( response.text )     ## prints html content

data = response.json()    ## error json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
  • 当我执行 request.json() 时,我得到一个错误 json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

  • 当我打印 request.content - 它返回带有 html 内容的 html 列表。 reponse.text 和 response.content 的输出是一样的。大量 li 标签被截断的 html 被返回:

<!DOCTYPE html>
<html>
<head>
<title>Data</title>
</head>
<div>
<ul>
<li>
body&nbsp;
<ul>
<li>items&nbsp;<ol>
<li>
<ul>
<li>name&nbsp;........ </li><li>messages&nbsp;<ol>
</ol></li></ul></div></body></html>

【问题讨论】:

    标签: python json request


    【解决方案1】:

    您试图从中获取 JSON 的 URL 似乎默认仅返回 HTML 页面。

    从您明确传递内容类型application/json 的 curl 请求中,因此您需要类似地更新您的请求语句,如下所示:

    response = requests.get(url, auth=(user, password), verify=False, 'headers': {'Content-Type': 'application/json'})
    

    注意:仅当您的 URL 实际返回 JSON 响应时,上述方法才有效。

    【讨论】:

    • 我使用了 headers={'Accept':'application/json'} 解决了这个问题。感谢您的提示。
    • @cool_stuff_coming 另外,最好使用 post 方法,因为您正在使用用户名和密码进行身份验证!
    【解决方案2】:

    headers={'Accept':'application/json'} 添加到 requests.get

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-05
      • 2021-08-06
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 2016-01-29
      • 1970-01-01
      • 2017-11-26
      相关资源
      最近更新 更多