Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: urllib2.HTTPError: HTTP Error 401: Unauthorized

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?

like image 996
stupidguy Avatar asked Apr 17 '12 17:04

stupidguy


People also ask

What is HTTP status 401 Unauthorized?

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.

Why am I getting a 401 Error?

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.

What is urllib2?

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.


1 Answers

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()
like image 183
big Avatar answered Sep 28 '22 05:09

big