python请求中的HTTP重定向代码3XX [英] Http Redirection code 3XX in python requests

查看:312
本文介绍了python请求中的HTTP重定向代码3XX的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试捕获http状态代码3XX/302作为重定向URL.但我无法获得它,因为它提供了200个状态代码.

I am trying to capture http status code 3XX/302 for a redirection url. But I cannot get it because it gives 200 status code.

这是代码:

import requests
r = requests.get('http://goo.gl/NZek5')
print r.status_code

我想这应该发出301或302,因为它重定向到另一个页面.我尝试了一些重定向网址(例如 http://fb.com ),但是它再次发布了200.应该采取什么措施来捕获重定向代码正确吗?

I suppose this should issue either 301 or 302 because it redirects to another page. I had tried few redirecting urls (for e.g. http://fb.com ) but again it is issuing the 200. What should be done to capture the redirection code properly?

推荐答案

requests为您处理重定向 ,请参见

requests handles redirects for you, see redirection and history.

如果您不希望requests处理重定向,请设置allow_redirects=False,或者您可以检查

Set allow_redirects=False if you don't want requests to handle redirections, or you can inspect the redirection responses contained in the r.history list.

演示:

>>> import requests
>>> url = 'https://httpbin.org/redirect-to'
>>> params = {"status_code": 301, "url": "https://stackoverflow.com/q/22150023"}
>>> r = requests.get(url, params=params)
>>> r.history
[<Response [301]>, <Response [302]>]
>>> r.history[0].status_code
301
>>> r.history[0].headers['Location']
'https://stackoverflow.com/q/22150023'
>>> r.url
'https://stackoverflow.com/questions/22150023/http-redirection-code-3xx-in-python-requests'
>>> r = requests.get(url, params=params, allow_redirects=False)
>>> r.status_code
301
>>> r.url
'https://httpbin.org/redirect-to?status_code=301&url=https%3A%2F%2Fstackoverflow.com%2Fq%2F22150023'

因此,如果allow_redirectsTrue,则说明已遵循重定向,并且返回的最终响应是进行重定向后的最后一页.如果allow_redirectsFalse,则返回第一个响应,即使它是重定向.

So if allow_redirects is True, the redirects have been followed and the final response returned is the final page after following redirects. If allow_redirects is False, the first response is returned, even if it is a redirect.

这篇关于python请求中的HTTP重定向代码3XX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆