[Tutor] urllib2.urlopen(url)

Martin Walsh mwalsh at groktech.org
Sun Apr 20 10:05:45 CEST 2008

Monika Jisswel wrote:
> Hi,
> can i stop urllib2.urlopen() from  following redirects automatically ?

It doesn't answer your question directly, but if you care more about the
initial request/response than the content at the other end of a redirect
-- you can use httplib. It might look something like this:

import urlparse
import httplib

url = urlparse.urlsplit('http://google.com/search?q=python')
host = url[1]
path = urlparse.urlunsplit(('', '')+url[2:])

con = httplib.HTTPConnection(host)
con.request('GET', path)
response = con.getresponse()

print 'status:', response.status
print 'reason:', response.reason
print 'document:', response.read()

You lose many advantages of the higher-level urllib2, as it does much of
the mundane work for you -- parsing urls, choosing http or https
transparently, etc -- but I think httplib is still appropriate if your
needs are simple.

More information here:


> thanks in advance
> Monika Jissvel

More information about the Tutor mailing list