Python:urllib2.HTTPError:HTTP错误401:未经授权

时间:2012-04-17 17:18:28

标签: python authentication

我正在尝试加载网页,但我遇到了这个问题。我有用户名和密码,但我不知道如何在python代码中使用它们。我查看了python教程,这就是我写的:

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

有什么不对吗?

2 个答案:

答案 0 :(得分:19)

这是工作代码

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()

答案 1 :(得分:5)

我认为您可以使用请求模块,这将使您更容易。

import requests
username = 'user'
password = 'pass'
url = 'http://www.example.com/index.html'
r = requests.get(url, auth=(username, password))  
page = r.content
print page