Python: Fetching HTTPS urls which require username/password authentication

It wasn't the easiest solution to find on the net, but a fairly simple one to implement.

Some solutions even suggest recompiling Python with OpenSSL installed. Sorry, too much trouble, not an option!

from urllib2 import URLError, HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, install_opener, build_opener

# Set up a HTTPS request with username/password authentication
# create a password manager
password_mgr = HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.
password_mgr.add_password(None, feed_url, "your_username", "your_password")
opener = build_opener(HTTPBasicAuthHandler(password_mgr))
file =

# After you get the "file", you pretty much work with it the same way as you normally would.
xml = etree.parse(file)

except URLError, e:
print 'URLError: "%s"' % e

Brush your hands off boys, we're done here.

Now to solve more pressing issues...

How to get that damn toilet tissue?


Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog