【问题标题】:Read https url from Python with basic access authentication使用基本访问身份验证从 Python 读取 https url
【发布时间】:2010-12-26 18:59:51
【问题描述】:

如何在 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'

【问题讨论】:

标签: python authentication https passwords


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        这从来没有让我失望过

        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
        

        【讨论】:

        • request.add_header('Authorization', b'Basic ' + base64.b64encode(username + b':' + password))
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-10
        • 1970-01-01
        • 1970-01-01
        • 2023-03-20
        相关资源
        最近更新 更多