我正在尝试使用urllib2下载受基本身份验证保护的页面.我正在使用python 2.7,但我也在另一台使用python 2.5的计算机上尝试过它,并遇到了完全相同的行为.我尽可能地遵循本指南中给出的示例,这是我生成的代码:
import urllib2
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, "http://authenticationsite.com/', "protected", "password")
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
f = opener.open("http://authenticationsite.com/content.html")
print f.read()
f.close()
Run Code Online (Sandbox Code Playgroud)
不幸的是服务器不是我的,所以我不能分享细节; 我把它们从上面和下面换了出来.当我运行它时,我得到以下Traceback:
File
"/usr/lib/python2.7/urllib2.py", line
397, in open
response = meth(req, response) File "/usr/lib/python2.7/urllib2.py",
line 510, in http_response
'http', request, response, code, msg, hdrs) File
"/usr/lib/python2.7/urllib2.py", line
435, in error
return self._call_chain(*args) File "/usr/lib/python2.7/urllib2.py",
line 369, in _call_chain
result = func(*args) File "/usr/lib/python2.7/urllib2.py", line
518, in http_error_default
raise HTTPError(req.get_full_url(), code,
msg, hdrs, …Run Code Online (Sandbox Code Playgroud)