How to force urllib2 not to use a proxy

If no proxy is explicitly specified, urllib2 will use Internet Explorer proxy settings by default. The issue is that urllib2 does not take into account the list of addresses which should be reached directly without a proxy, e.g. localhost or the local LAN. In some situations, this means that only external addresses can be reached.

It is possible to force urllib2 not to use any proxy, but this is not explained in the official Python documentation.
The trick is to use a proxy handler with an empty dictionary. It was found here: http://mail.python.org/pipermail/python-list/2005-January/304424.html

Here is an example to remove proxy settings for all requests:

proxy_handler = urllib2.ProxyHandler({})
opener = urllib2.build_opener(proxy_handler)
urllib2.install_opener(opener)

And here is an example for only one request:

proxy_handler = urllib2.ProxyHandler({})
opener = urllib2.build_opener(proxy_handler)
req = urllib2.Request('http://...')
r = opener.open(req)
result = r.read()

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Thank you so much, You just

Thank you so much,
You just saved my life :)

Awesome !!!

Thanks. It worked.