I was trying to load a web page, but I ran into this problem. I do have the username and password, but I don't know how to use them in python code. I looked up on python tutorial, and this is what I wrote:
import urllib2
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
username = 'user'
password = 'pass'
top_level_url = "www.something.com:80"
password_mgr.add_password(None, top_level_url, username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)
opener.open('http://www.something.com/h/h.html')
urllib2.install_opener(opener)
response = urllib2.urlopen()
page = response.read()
print page
Anything wrong?
The HyperText Transfer Protocol (HTTP) 401 Unauthorized response status code indicates that the client request has not been completed because it lacks valid authentication credentials for the requested resource.
What is a 401 Unauthorized Error? A 401 Unauthorized Error is an HTTP status code that indicates that the server received an unverified request. In human terms, this means that the website you're trying to access won't load until you log-in with a valid user ID and password.
Urllib package is the URL handling module for python. It is used to fetch URLs (Uniform Resource Locators). It uses the urlopen function and is able to fetch URLs using a variety of different protocols.
Here is working code
import urllib2
url = 'http://www.abc.com/index.html'
username = 'user'
password = 'pass'
p = urllib2.HTTPPasswordMgrWithDefaultRealm()
p.add_password(None, url, username, password)
handler = urllib2.HTTPBasicAuthHandler(p)
opener = urllib2.build_opener(handler)
urllib2.install_opener(opener)
page = urllib2.urlopen(url).read()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With