在Python中连接到URL

4 投票
3 回答
8761 浏览
提问于 2025-04-16 10:03

我正在尝试用以下代码连接到一个网址,并且需要输入用户名和密码:

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

但是我遇到了这个问题:

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

有没有人知道这是怎么回事?

3 个回答

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
2

你应该使用 urllib.request.HTTPBasicAuthHandler 来进行HTTP认证。

HTTP协议并不是通过 user:password@host 这种方式来处理认证的。

5

抱歉,我没注意到你在用py3k版本的Python。
你可以查看这个链接:urllib.request - FancyURLopener。我个人对py3k不太熟悉。
简单来说,你需要创建一个新的类,继承自urllib.request.FancyURLopener,然后重写prompt_user_passwd(host, realm)这个方法,最后调用YourClass.urlopen(url)来使用。

下面的内容是关于py2的。

这是你需要的,urllib2 - 基本认证
下面是那页面的代码,以防将来链接失效。

# 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)

撰写回答