How to disable automatic redirects in python3 urllib.request?
Asked Answered
A

1

7

Python3 urllib.request does the 301/302 redirects automatically, how can you disable this behaviour?

Araarab answered 29/8, 2018 at 22:15 Comment(0)
A
12

The library "requests" makes it easier, but if you need or want to use urllib.request, this works:

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))
Araarab answered 29/8, 2018 at 22:15 Comment(2)
If the question is "how to I achieve X with library Y", the answer should not be "it's simple, use library Z".Bedell
Is this documented somewhere in the python docs?Coffle

© 2022 - 2024 — McMap. All rights reserved.