您的位置: 网站首页> requests爬虫> 当前文章

requests的url重定向次数与禁用处理

老董-我爱我家房产SEO2019-07-18162围观,137赞

  url重定向也是网站常见的操作,比如在网站改版中把老版本的url重定向到新版本的url,把http协议的站点重定向到https协议的站点。重定向一般是301或者302重定向。我们打开http://www.baidu.com,他们重定向到https://www.baidu.com

  1、如何实现url重定向

在默认情况下,除了HEAD请求, Requests会自动处理所有重定向。可以使用响应对象的history方法来追踪重定向。

# -*- coding: utf-8 -*-
import requests

headers = {
'user-agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36 Edg/95.0.1020.44',
}

r = requests.get("http://www.baidu.com", headers=headers)
print(r.history) # 重定向历史
print(r.url) # 最后请求的url
print(r.status_code)
[<Response [302]>]
https://www.baidu.com/
200

  2、url重定向可以多次跟进吗

  Response.history是一个Response对象的列表,这个对象列表按照从开始到结束发生的请求进行排序,我们看1个2次重定向的案例。(我无法确定requests最大会跟进几次重定向,有兴趣可以看源码来找到答案。)

# -*- coding: utf-8 -*-

headers = {
'user-agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36 Edg/95.0.1020.44',
}

r = requests.get("https://bj.5i5j.com/rent", headers=headers)
print(r.history) # 重定向历史
print(r.url) # 最后请求的url
print(r.status_code)
[<Response [301]>, <Response [301]>]
https://bj.5i5j.com/zufang/
200

  3、如何禁用url重定向

  在GET、OPTIONS、POST、PUT、PATCH或者 DELETE请求中如果不想重定向,那么可以通过allow_redirects参数禁用重定向,如果是HEAD请求,可以allow_redirects=True来启用重定向

# -*- coding: utf-8 -*-

r = requests.get("https://bj.5i5j.com/rent",allow_redirects=False)
print(r.history) # 重定向历史
print(r.url) # 最后请求的url
print(r.status_code)
[]
https://bj.5i5j.com/rent
301

很赞哦!

python编程网提示:转载请注明来源www.python66.com。
有宝贵意见可添加站长微信(底部),获取技术资料请到公众号(底部)。同行交流请加群 python学习会

文章评论

    requests的url重定向次数与禁用处理文章写得不错,值得赞赏

站点信息

  • 网站程序:Laravel
  • 客服微信:a772483200