如何在python3 urllib.request中禁用自动重定向?

时间:2018-08-29 22:15:20

标签: python-3.x urllib

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

1 个答案:

答案 0 :(得分: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))