Python: Fetching HTTPS urls which require username/password authentication

0 Comments

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!

01.from urllib2 import URLError, HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, install_opener, build_opener
02. 
03.# Set up a HTTPS request with username/password authentication
04.try:
05.  # create a password manager
06.  password_mgr = HTTPPasswordMgrWithDefaultRealm()
07. 
08.  # Add the username and password.
09.  password_mgr.add_password(None, feed_url, "your_username", "your_password")
10.  opener = build_opener(HTTPBasicAuthHandler(password_mgr))
11.  file = opener.open(feed_url)
12. 
13.  # After you get the "file", you pretty much work with it the same way as you normally would.
14.  xml = etree.parse(file)
15. 
16.except URLError, e:
17.  print 'URLError: "%s"' % e
18.  raise

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

Now to solve more pressing issues...

ExtRS
How to get that damn toilet tissue?

Source

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