使用基本访问身份验证从Python读取https url

时间:2009-12-15 12:02:58

标签: python authentication https passwords

如何在Python中打开https url?

import urllib2

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

给出:

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:5)

请阅读urllib2密码管理器和基本身份验证处理程序以及摘要身份验证处理程序。

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

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

您的urllib2脚本实际上必须提供足够的信息来进行HTTP身份验证。用户名,密码,域名等

答案 2 :(得分:3)

如果您想将用户名和密码信息传递给urllib2,则需要使用HTTPBasicAuthHandler

Here's a tutorial showing you how to do it.

答案 3 :(得分:2)

您无法将凭据传递给urllib2.open。在您的情况下,user被解释为域名,而password@domain.com被解释为端口号。