Is there an easy way to request a URL in python and NOT follow redirects?

John picture John · Sep 21, 2008 · Viewed 71.1k times · Source

Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.

Answer

Marian picture Marian · Feb 3, 2013

Here is the Requests way:

import requests
r = requests.get('http://github.com', allow_redirects=False)
print(r.status_code, r.headers['Location'])