我正在尝试使用以下代码连接到包含用户名和密码的网址:
urllib.request.urlopen("http://username:password@......etc...", None)
但我正在
urllib.error.URLError: urlopen error [Errno 11003] getaddrinfo failed
任何人都知道发生了什么事?
答案 0 :(得分:5)
对不起我没注意到你在使用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)
答案 1 :(得分:2)
您应该使用urllib.request.HTTPBasicAuthHandler
进行HTTP身份验证。
HTTP不以user:password@host
方式处理身份验证。
答案 2 :(得分:1)
如果您可以安装第三方库,那么httplib2
更易于使用,并且是urllib.request
的更强大的替代方案:
import httplib2
h = httplib2.Http("/path/to/cache-directory")
h.add_credentials(username, password)
response, content = h.request(url)
assert response.status == 200