守护麦田  

Requests 请求,有时候A会发生请求网址 B,但是网址B 没有直接给反馈,通知了网址C,网址C 给了 请求网址A 响应。 这就是重定向、

重定向:就是通过各种方法将各种网络请求重新定个方向转到其它位置,从地址A跳转到地址B了。

重定向状态码:301---临时重定向; 302 ---永久重定向;

有个博客园 中抓包到的请求,就是重定向。

url = https://i.cnblogs.com/EditPosts.aspx?opt=1

抓包如下:

 

 

 python 中代码如下:

这个请求中的 关键是:
allow_redirects=True,requests 自动进行重定向处理; 这样,就无法查看进行重定向处理前 返回的headers 中location信息了。
要查看重定向处理前的URL,返回,需将 allow_redirects=False,requests 不进行重定向处理。代码如下:

可以捕捉到 响应 headers 中Location,到的新url。
代码如下:
urlB = "https://i.cnblogs.com/EditPosts.aspx?opt=1"
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0"}
s = requests.session()
logging.captureWarnings(True)
re = s.get(url=urlB,
headers=headers,
allow_redirects=True,
verify=False)
print(re.status_code)

or:re = s.get(url=urlB,
           headers=headers,
allow_redirects=False,
verify=False)
print(re.status_code)
new_url = re.headers["Location"]
print(new_url)
故,遇到重定向URL时,如果希望 Requests 主动进行重定向处理:

allow_redirects=True,请求过去后,遇到重定向,将主动请求 重定向后的新url,并返回新URL的响应;
如果,不希望 进行处理,想捕捉 重定向后的URL,使用
allow_redirects=False,打印响应 headers 中的Location。
一般遇到重定向,不加 allow_redirects参数的话,Requests库默认 值为True,主动进行重定向后的请求。
 
 
posted on 2020-11-06 16:48  守护麦田  阅读(1737)  评论(0编辑  收藏  举报