连接到python中的url

2024-05-20 00:04:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用用户名和密码连接到具有以下代码的url:

urllib.request.urlopen("http://username:password@......etc...", None)

但是我得到了

urllib.error.URLError: urlopen error [Errno 11003] getaddrinfo failed

有人知道怎么回事吗?


Tags: 代码nonehttpurl密码requestetcusername
3条回答

对不起。我没注意到你在使用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)

如果您可以安装第三方库,那么^{}^{}更易于使用,也更强大:

import httplib2

h = httplib2.Http("/path/to/cache-directory")
h.add_credentials(username, password)
response, content = h.request(url)
assert response.status == 200

您应该使用^{}进行HTTP身份验证。

HTTP不以user:password@host方式处理身份验证。

相关问题 更多 >