我正在尝试使用以下代码连接到具有用户名和密码的URL:
urllib.request.urlopen("http://username:password@......etc...", None)
但我得到了
urllib.error.URLError: urlopen error [Errno 11003] getaddrinfo failed
有谁知道怎么了?
解决方法:
对不起.我没注意到你在使用py3k.
见urllib.request – FancyURLopener.我个人不太了解py3k.
基本上,您需要子类化urllib.request.FancyURLopener,覆盖prompt_user_passwd(host,realm),然后调用YourClass.urlopen(url).
下面是py2
这就是你想要的,urllib2 – Basic Authentication
下面是该页面的代码,以防万一有些日子链接腐烂.
# 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)
标签:python,http,authentication,python-3-x