Python: Accessing a web page with basic authentication

Here I’m demonstrating on how to access a web page with basic authentication in PYTHON code. This is very simple python code example using urllib2 module and no third party modules being used. 

Using this code you can access any web link from your code and get return data from that link. This is like web proxy call 


 

import urllib2

accessURL = ‘https://remoteserver.com/accesspage’
pwdmanager = urllib2.HTTPPasswordMgrWithDefaultRealm()
pwdmanager.add_password(None, accessURL, “username”, “password”)
authhandler = urllib2.HTTPBasicAuthHandler(pwdmanager)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
returnPage = urllib2.urlopen(accessURL).read()

print returnPage


You can also send data to that URL call and get return data if that link returns. 


 

import urllib2

accessURL = ‘https://remoteserver.com/accesspage’
pwdmanager = urllib2.HTTPPasswordMgrWithDefaultRealm()
pwdmanager.add_password(None, accessURL, “username”, “password”)
authhandler = urllib2.HTTPBasicAuthHandler(pwdmanager)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
requestdata = urllib.urlencode({‘FIRST_NAME’ : ‘Sumant’,’LAST_NAME’ : ‘Kuchipudi’})
responsedata = urllib2.urlopen(accessURL, data=requestdata).read()

print responsedata


 

I hope this helps you

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: