python-requests:限制重定向次数 [英] python-requests: Limit Number of Redirects Followed

查看:132
本文介绍了python-requests:限制重定向次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法限制执行 GET 时 python 请求将遵循的重定向次数?

Is there a way to limit the number of redirects that python-requests will follow when performing a GET?

我知道 allow_redirects=False,但这只会阻止重定向.我正在寻找一种跟踪重定向的方法,最多可达一些最大跃点数.

I know about allow_redirects=False, but that just prevents redirects all together. I'm looking for a way to follow redirects, up to some maximum number of hops.

# What I know how to do:
resp = requests.get(url)  # follows redirects "infinitely"
resp = requests.get(url, allow_redirects=False)  # follows no redirects

# What I'm trying to do:
resp = requests.get(url, max_redirects=3)  # follow up to 3 redirects

谢谢!

推荐答案

你必须创建 Session 对象并将 max_redirects 变量设置为 3

You have to create Session object and set max_redirects variable to 3

session = requests.Session()
session.max_redirects = 3
session.get(url)

TooManyRedirects 如果请求超过最大重定向次数,则会引发异常.

TooManyRedirects exception will be raised if a requests exceeds maximum number of redirects.

相关的 github 问题讨论了为什么不能为每个请求设置 max_redirects https://github.com/kennethreitz/requests/issues/1300

Related github issue discussing why you can not set max_redirects per request https://github.com/kennethreitz/requests/issues/1300

这篇关于python-requests:限制重定向次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆