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://*.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://*.com/q/22150023'
>>> r.url
'https://*.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%2F*.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.