python3 重定向,python请求中的HTTP重定向代码3XX

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.

Here is the code:

import requests

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

print r.status_code

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 handles redirects for you, see redirection and history.

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.

Demo:

>>> 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

[, ]

>>> 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'

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值