# create a password manager
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of None.
top_level_url = "http://example.com/foo/"
password_mgr.add_password(None, top_level_url, username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
# create "opener" (OpenerDirector instance)
opener = urllib2.build_opener(handler)
# use the opener to fetch a URL
opener.open(a_url)
# Install the opener.
# Now all calls to urllib2.urlopen use our opener.
urllib2.install_opener(opener)
对不起。我没注意到你在使用py3k。
见urllib.request - FancyURLopener。我个人对py3k不太了解。
基本上,您需要对
urllib.request.FancyURLopener
进行子类划分,覆盖prompt_user_passwd(host, realm)
,然后调用YourClass.urlopen(url)
。下面是py2
这就是你想要的,urllib2 - Basic Authentication
下面是该页面的代码,以防有一天链接腐烂
如果您可以安装第三方库,那么^{} 比^{} 更易于使用,也更强大:
您应该使用^{} 进行HTTP身份验证。
HTTP不以
user:password@host
方式处理身份验证。相关问题 更多 >
编程相关推荐