使用基本访问认证从Python读取HTTPS网址

4 投票
4 回答
14889 浏览
提问于 2025-04-15 17:02

在Python中,如何打开https网址呢?

import urllib2

url = "https://user:password@domain.com/path/
f = urllib2.urlopen(url)
print f.read()

结果是:

httplib.InvalidURL: nonnumeric port: 'password@domain.com'

4 个回答

3

如果你想把用户名和密码信息传递给 urllib2,你需要使用一个叫 HTTPBasicAuthHandler 的工具。

这里有个教程教你怎么做。

11

这个方法一直都很有效

import urllib2, base64
username = 'foo'
password = 'bar'
auth_encoded = base64.encodestring('%s:%s' % (username, password))[:-1]

req = urllib2.Request('https://somewebsite.com')
req.add_header('Authorization', 'Basic %s' % auth_encoded)
try:
    response = urllib2.urlopen(req)
except urllib2.HTTPError, http_e:
    # etc...
    pass
5

请了解一下urllib2中的密码管理器,以及基本的身份验证处理器和摘要身份验证处理器。

http://docs.python.org/library/urllib2.html#abstractbasicauthhandler-objects

http://docs.python.org/library/urllib2.html#httpdigestauthhandler-objects

你的urllib2脚本必须提供足够的信息来进行HTTP身份验证,比如用户名、密码、域名等等。

撰写回答