
python `requests`库在默认情况下会自动跟随http重定向,导致无法直接获取到3xx系列的状态码,而是返回最终的200状态码。本教程将详细解释这一机制,并提供通过设置`allow_redirects=false`参数来禁用自动重定向的方法,从而准确捕获并处理原始的重定向响应码。
理解Requests库的重定向行为
在使用python的requests库进行HTTP请求时,我们常常期望获取到网页的最终内容。为了实现这一目标,requests库在设计上默认会遵循HTTP重定向(例如301、302、303等状态码)。这意味着当您向一个会发生重定向的URL发起GET请求时,requests会自动跟踪这些重定向,直到达到一个非重定向的最终目标URL,并返回该最终URL的响应。
这种默认行为在多数情况下是方便的,因为它简化了获取目标资源的过程。然而,当我们需要精确地检测和处理重定向本身,例如识别一个URL是否是重定向链接,或者获取原始的重定向状态码(如302 Found、301 Moved Permanently),默认行为就会导致问题。此时,response.status_code将显示最终页面的状态码(通常是200 OK),而不是原始的重定向状态码。
捕获原始重定向状态码的方法
要捕获原始的HTTP重定向状态码,我们需要指示requests库不要自动跟随重定向。这可以通过在requests.get()(或其他HTTP方法,如post()、head()等)中设置allow_redirects=False参数来实现。
当allow_redirects设置为False时,requests库在收到任何3xx状态码的响应时,将不会继续发起新的请求,而是直接返回这个3xx响应。这样,我们就可以通过response.status_code获取到原始的重定向状态码。
立即学习“Python免费学习笔记(深入)”;
示例代码
下面是一个示例,演示如何使用allow_redirects=False来获取重定向状态码,并与默认行为进行对比:
import requests def get_url_redirect_status(url: str, follow_redirects: bool = False) -> str: """ 获取URL的HTTP状态码,并根据follow_redirects参数决定是否跟随重定向。 参数: url (str): 待检测的URL。 follow_redirects (bool): 是否允许requests库自动跟随重定向。 设置为False可捕获原始的3xx状态码。 返回: str: 包含状态码和描述的字符串。 """ try: # 核心:通过 allow_redirects 参数控制重定向行为 response = requests.get(url, timeout=5, allow_redirects=follow_redirects) status_code = response.status_code if 200 <= status_code < 300: return f"正常响应 ({status_code})" elif 300 <= status_code < 400: # 如果是3xx状态码,表示发生了重定向 # response.headers['location'] 可以获取重定向目标 redirect_target = response.headers.get('Location', '未知') return f"重定向 ({status_code}) -> 目标: {redirect_target}" elif 400 <= status_code < 500: return f"客户端错误 ({status_code})" elif 500 <= status_code < 600: return f"服务器错误 ({status_code})" else: return f"其他状态 ({status_code})" except requests.exceptions.Timeout: return "错误: 请求超时" except requests.exceptions.ConnectionError: return "错误: 连接失败" except requests.exceptions.RequestException as e: return f"错误: {e}" # 示例用法 if __name__ == "__main__": # 使用 httpbin.org 提供的测试URL,它会发生302重定向到 /get test_redirect_url = "http://httpbin.org/redirect-to?url=http://httpbin.org/get" test_ok_url = "http://httpbin.org/status/200" test_not_found_url = "http://httpbin.org/status/404" print("--- 禁用自动重定向 (allow_redirects=False) ---") print(f"URL: {test_redirect_url}") print(f"状态: {get_url_redirect_status(test_redirect_url, follow_redirects=False)}n") print(f"URL: {test_ok_url}") print(f"状态: {get_url_redirect_status(test_ok_url, follow_redirects=False)}n") print(f"URL: {test_not_found_url}") print(f"状态: {get_url_redirect_status(test_not_found_url, follow_redirects=False)}n") print("n--- 对比:默认行为 (自动跟随重定向) ---") try: response_default = requests.get(test_redirect_url, timeout=5) print(f"URL: {test_redirect_url}") print(f"默认行为状态码: {response_default.status_code}") # 通过 response.history 可以查看重定向链 if response_default.history: print(f"重定向历史: {[f'{r.status_code} -> {r.url}' for r in response_default.history]}") print(f"最终URL: {response_default.url}") else: print("未发生重定向。") except requests.exceptions.RequestException as e: print(f"错误: {e}")
运行上述代码,您会发现:
- 当follow_redirects=False时,test_redirect_url会返回重定向 (302) -> 目标: http://httpbin.org/get,这正是我们想要捕获的原始重定向状态。
- 当使用默认行为(即requests.get(url)或follow_redirects=True)时,test_redirect_url会返回最终的200状态码,并且response.history会记录重定向的路径。
注意事项
- 重定向目标获取:当allow_redirects=False且响应为3xx状态码时,重定向的目标URL通常可以在response.headers[‘Location’]中找到。
- 重定向历史:即使禁用了自动重定向,如果您想了解一个URL是否会重定向以及重定向的路径,可以先设置allow_redirects=False获取原始3xx响应,然后手动发起对Location头中URL的请求。或者,如果您允许自动重定向 (allow_redirects=True),response.history属性会包含一个Response对象列表,按请求的顺序记录了所有重定向响应。
- HEAD请求:对于某些场景,如果只是想检查URL是否存在或是否重定向,而不关心响应内容,可以使用requests.head(url, allow_redirects=False)。HEAD请求通常比GET请求更快,因为它只请求响应头,但并非所有服务器都正确支持HEAD请求。
- 超时设置:在进行网络请求时,务必设置timeout参数,以防止程序因长时间等待响应而阻塞。
- 异常处理:网络请求容易遇到各种问题(如连接失败、超时等),因此良好的异常处理是必不可少的。requests.exceptions模块提供了多种具体的异常类型供捕获。
总结
requests库的allow_redirects参数是控制HTTP重定向行为的关键。通过将其设置为False,开发者可以精确地捕获并处理原始的3xx重定向状态码,这对于需要分析链接健康状况、构建爬虫策略或进行特定网络诊断的场景至关重要。理解并灵活运用这一参数,将使您的Python网络请求代码更加健壮和功能完善。


