
python `requests`库在默认情况下会自动跟随http重定向,导致无法直接获取到3xx系列的状态码,而是返回最终的200状态码。本教程将详细解释这一机制,并提供通过设置`allow_redirects=false`参数来禁用自动重定向的方法,从而准确捕获并处理原始的重定向响应码。
在使用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}")运行上述代码,您会发现:
requests库的allow_redirects参数是控制HTTP重定向行为的关键。通过将其设置为False,开发者可以精确地捕获并处理原始的3xx重定向状态码,这对于需要分析链接健康状况、构建爬虫策略或进行特定网络诊断的场景至关重要。理解并灵活运用这一参数,将使您的Python网络请求代码更加健壮和功能完善。
以上就是如何在Python Requests库中获取HTTP重定向状态码(3xx)的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号