默认情况下,除了head请求,requests会自动处理重定向
重定向就是会把url重新指定到另一个。比如github,使用http会自动重定向到https。一些公司也会使用网关啥的做重定向。
r = requests.get('http://github.com')
print(r.url)
print(r.status_code)
print(r.history)

可以看出url中http变成了https,使用histroy可以追踪重定向
如果不想要使用重定向,可以在请求中使用allow_redirects参数来禁用重定向处理,False禁用,True开启
r = requests.get('http://github.com',allow_redirects=False)
print(r.url)
print(r.status_code)
print(r.history)

可以看出url没有变,状态码提示301:重定向
当使用head请求时,是自动默认不启用重定向的,其他请求是默认启用重定向的
r = requests.head('http://github.com')
print(r.url)
print(r.status_code)
print(r.history)

使用allow_redirects参数来开启重定向
import requests
from requests import exceptions
r = requests.head('http://github.com',allow_redirects = True)
print(r.url)
print(r.status_code)
print(r.history)

本文详细介绍了Python的requests库如何处理HTTP重定向,默认情况下除HEAD请求外,其他请求都会自动处理重定向。文章通过示例代码展示了如何使用allow_redirects参数控制是否启用重定向,并对比了不同设置下请求的行为差异。

64万+

被折叠的 条评论
为什么被折叠?



