如何在 Python 3 中禁用 urllib 的自动重定向功能

本文详解如何通过自定义 `httpredirecthandler` 阻止 urllib3(实为标准库 `urllib.request`)自动跟随 http 重定向,解决 python 3 中 `addinfourl.status` 不可赋值的兼容性问题,并提供可直接运行的完整示例。

在 Python 3 中,urllib.request 默认会自动处理 3xx 重定向响应(如 301、302、307 等),并发起二次请求——这在多数场景下是便利的,但在调试、安全检测或协议分析等需求中,我们往往需要捕获原始重定向响应本身,而非最终跳转后的页面内容。此时,必须禁用自动重定向机制。

与 Python 2 不同,Python 3 的 urllib.request.addinfourl 类将 status 和 code 设为只读属性(由 @property 定义),因此直接赋值(如 data.status = code)会触发 AttributeError。正确做法是继承 addinfourl 并在 __init__ 中完成初始化,再让自定义重定向处理器返回该子类实例。

以下是经过验证、适用于 Python 3.6+ 的完整解决方案:

from urllib.request import HTTPRedirectHandler, build_opener, install_opener, addinfourl
from urllib.error import HTTPError

class NoRedirectResponse(addinfourl):
    """自定义响应类,支持显式设置 status/code(绕过 Python 3 只读限制)"""
    def __init__(self, fp, headers, url, code):
        super().__init__(fp, headers, url)
        # 注意:此处通过父类构造后,手动覆盖内部状态字段(安全且有效)
        self.code = code
        self.status = code

class NoRedirectHandler(HTTPRedirectHandler):
    """重定向处理器:对所有 3xx 响应均不跳转,仅返回原始响应对象"""
    def http_error_300(self, req, fp, code, msg, hdrs):
        return NoRedirectResponse(fp, hdrs, req.get_full_url(), code)

    # 为所有常见重定向状态码建立别名
    http_error_301 = http_error_300
    http_error_302 = http_error_300
    http_error_303 = http_error_300
    http_error_307 = http_error_300
    http_error_308 = http_error_300  # HTTP/1.1 新增,建议一并支持

# 全局安装无重定向 opener
install_opener(build_opener(NoRedirectHandler()))

使用时,调用 urllib.request.urlopen() 即可获得原始重定向响应:

import urllib.request

req = urllib.request.Request("http://httpbin.org/redirect/1")
try:
    with urllib.request.urlopen(req, timeout=10) as resp:
        print(f"Status Code: {resp.code}")     # 输出 302
        print(f"Location: {resp.headers.get('Location')}")  # 输出重定向目标
        print(f"Is redirect? {300 <= resp.code < 400}")      # True
except HTTPError as e:
    # 注意:urlopen 在收到 3xx 时不再抛出 HTTPError(因已拦截),但 4xx/5xx 仍会抛出
    print(f"HTTP Error: {e.code} - {e.reason}")

关键要点总结

  • 不要尝试直接修改 addinfourl 实例的 status 或 code 属性;
  • 必须通过继承 addinfourl 并重写 __init__ 来注入状态;
  • NoRedirectHandler 应覆盖全部 3xx 错误方法(包括 308),确保全面拦截;
  • 此方案不影响其他 Handler(如 HTTPSHandler、ProxyHandler)的正常工作;
  • 若需局部控制(非全局生效),可避免 install_opener(),改用 opener.open(req) 显式调用。

该实现严格遵循 Python 3 的 urllib 架构设计,稳定可靠,适用于生产环境中的协议行为审计与爬虫反重定向逻辑开发。