Python+requests重定向历史查看

一、什么是重定向

重定向就是网络请求被重新定个方向转到了其它位置

二、为什么要做重定向

网页重定向的情况一般有:网站调整(如网页目录结构变化)、网页地址改变、网页扩展名(.php、.html、.asp)的改变、当一个网站注册了多个域名的时候。这些情况下都需要进行网页的重定向。不做重定向的话就容易出现404错误(如访问网上提供的网页url经常报404错误,就是有可能url地址改变了但没有做重定向导致的。)

三、Python+requests重定向操作

1、重定向分:301 redirect—》永久性重定向、302 redirect—》暂时性重定向,比如下图的302永久性重定向
Python+requests重定向历史查看

2、追踪重定向

import requests
url = ‘http://home.cnblogs.com/u/xswt/’
r = requests.get(url,params=None,headers={‘Content-Type’:‘application/json’})
print(r.history)#history追踪页面重定向历史
运行结果:

[<Response [301]>, <Response [302]>, <Response [302]>, <Response [302]>]
#可以看到该请求做了多次重定向
3、Python+requests获取重定向的url地址:

import requests
url = ‘http://home.cnblogs.com/u/xswt/’
r = requests.get(url,headers={“Content-Type”:“application/json”})
reditList = r.history#可以看出获取的是一个地址序列
print(f’获取重定向的历史记录:{reditList}’)
print(f’获取第一次重定向的headers头部信息:{reditList[0].headers}’)
print(f’获取重定向最终的url:{reditList[len(reditList)-1].headers[“location”]}’)

运行结果:
获取重定向的历史记录:[<Response [301]>, <Response [302]>, <Response [302]>, <Response [302]>]
获取第一次重定向的headers头部信息:{‘Date’: ‘Fri, 06 Sep 2019 06:53:05 GMT’, ‘Content-Length’: ‘0’, ‘Connection’: ‘keep-alive’, ‘Location’: ‘https://home.cnblogs.com/u/xswt/’}
获取重定向最终的url:https://account.cnblogs.com/signin?returnUrl=http%3a%2f%2fhome.cnblogs.com%2fu%2fxswt%2f
4、Python+requests重启和禁止重定向

‘’’
禁止重定向(all_redirects=False)
‘’’
import requests
url = ‘http://home.cnblogs.com/u/xswt/’
r = requests.get(url,headers={“Content-Type”:“application/json”},allow_redirects=False)
print(r.status_code)
print(r.text)
复制代码
运行结果:

301

‘’’
重启重定向
‘’’
import requests
url = ‘https://www.csdn.net/’
r = requests.get(url,headers={“Content-Type”:“application/json”},allow_redirects=True)
print(r.status_code)
print(r.text)