【问题标题】:request.get(url) returns empty contentrequest.get(url) 返回空内容
【发布时间】:2014-08-25 18:08:56
【问题描述】:

我正在尝试解决这个问题,但没有运气:

import requests
r = requests.get('http://example.com/m7ppct4', allow_redirects=True)

r.status_code 返回200r.content 返回''

r.headers 返回以下字典:

{'content-length': '0', 
 'content-language': 'en-US', 
 'x-powered-by': 'Servlet/3.0', 
 'set-cookie': '__cfduid=d4b3d47d43189ac72be14b1d2a2bed98a1408989649815; expires=Mon, 23-Dec-2019 23:50:00 GMT; path=/; domain=.azdoa.gov; HttpOnly, LWJSESSIONID=0000SESSIONMANAGEMENTAFFINI:18h1v85u3; Path=/; HttpOnly, NSC_batubufkpctWTTTM=ffffffff09f39f1545525d5f4f58455e445a4a42378b;expires=Mon, 25-Aug-2014 18:02:49 GMT;path=/;secure;httponly', 
 'expires': 'Thu, 01 Dec 1994 16:00:00 GMT', 
 'server': 'cloudflare-nginx', 
 'connection': 'keep-alive', 
 'x-ua-compatible': 'IE=EmulateIE9', 
 'cache-control': 'no-cache="set-cookie, set-cookie2"', 
 'date': 'Mon, 25 Aug 2014 18:00:49 GMT', 
 'cf-ray': '15f9b0ff50cf0d6d-LAX', 
 'content-type': 'application/octet-stream'}

当我在浏览器中打开页面时,我清楚地看到了内容。

关于如何进行调试有什么想法吗?我想通过requests.get() 调用获取页面内容。

【问题讨论】:

  • 您使用的是什么版本的请求?
  • requests.__version__ 返回'2.3.0'
  • 原来是allow_redirects,我在想
  • 此处输入错误。我在代码中得到了正确的。谢谢你指出这一点。已更正。

标签: python python-requests


【解决方案1】:

您必须发送任何用户代理:

import requests
r = requests.get('http://example.com/m7ppct4',  headers={'User-Agent':'test'})

【讨论】:

    【解决方案2】:

    看起来由 tinyurl (azstatejobs) 链接的网站根据用户代理过滤请求。欺骗 Chrome 用户代理对我有用:

    import requests
    url = 'http://tinyurl.com/m7ppct4'
    user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36'
    headers = {'User-Agent': user_agent}
    r = requests.get(url, headers=headers)
    

    allow_redirect默认为真)

    您可能想尝试不同的用户代理,看看是什么让该网站不像 python 请求用户代理。

    【讨论】:

    • 我认为 tinyurl 可以用于我当前的用户代理,因为我将它用于其他 url 没有问题。也许最终的 url 不喜欢我现在的。感谢您指出这一点。
    • 添加用户代理字符串解决了这个问题。谢谢。
    【解决方案3】:
    import requests
    import json
    import pprint
    
    
    r = requests.get('URL')
    pprint.pprint(json.loads(r.content))
    

    【讨论】:

      【解决方案4】:

      除了缺少 user-agent 标头之外,问题还可能与缺少身份验证详细信息有关。

      例如下面的代码返回空结果:

      import requests
      
      host = 'http://localhost:2080'
      path = '/rest/api/2/project'
      res = requests.get(f'{host}{path}')
      print(res.json())
      

      然后,使用用户名和密码添加身份验证解决了这个问题:

      from requests.auth import HTTPBasicAuth
      import requests
      
      host = 'http://localhost:2080'
      path = '/rest/api/2/project'
      res = requests.get(f'{host}{path}', auth = HTTPBasicAuth('user', 'pass'))
      print(res.json())
      

      【讨论】:

        猜你喜欢
        • 2014-09-25
        • 1970-01-01
        • 1970-01-01
        • 2023-04-02
        • 2016-08-05
        • 2014-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多