request.get(url)返回空内容

6

我正在努力理解这个问题,但是没有成功:

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? - Padraic Cunningham
requests.__version__ 返回 '2.3.0' - Tammo Heeren
1
所以它是 allow_redirects,我在想。 - Padraic Cunningham
打错了,我在代码里已经改正了。谢谢你指出来。已经修正。 - Tammo Heeren
4个回答

11

看起来由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 请求用户代理。


1
我认为TinyURL对我的当前用户代理是可以的,因为我在使用其他网址时没有问题。也许最终的网址不喜欢我的当前用户代理。感谢您指出这一点。 - Tammo Heeren
用户代理字符串的添加解决了问题。谢谢。 - Tammo Heeren

10

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

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

1
import requests
import json
import pprint


r = requests.get('URL')
pprint.pprint(json.loads(r.content))

0

问题可能与缺少身份验证详细信息以及缺少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())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接