【问题标题】:How to disable automatic redirects in python3 urllib.request?如何在 python3 urllib.request 中禁用自动重定向?
【发布时间】:2018-08-29 22:15:19
【问题描述】:

Python3 urllib.request 会自动进行 301/302 重定向,如何禁用此行为?

【问题讨论】:

    标签: python-3.x urllib


    【解决方案1】:

    库“requests”使它更容易,但如果您需要或想要使用 urllib.request,这很有效:

    from urllib import request
    import urllib.error
    
    class NoRedirect(request.HTTPRedirectHandler):
        def redirect_request(self, req, fp, code, msg, headers, newurl):
            return None
    
    
    opener = request.build_opener(NoRedirect)
    request.install_opener(opener)
    
    try:
        r = request.urlopen('http://google.com')
    except urllib.error.HTTPError as e:
        r = e
    
    print(r.status)
    print(dir(r))
    

    【讨论】:

    • 如果问题是“我如何使用库 Y 实现 X”,那么答案不应该是“很简单,使用库 Z”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 2017-12-07
    • 1970-01-01
    • 2016-07-02
    相关资源
    最近更新 更多