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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1906977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:18:48  来源:igfitidea点击:

Read https url from Python with basic access authentication

pythonauthenticationhttpspasswords

提问by Etam

How do you open https url in Python?

你如何在 Python 中打开 https url?

import urllib2

url = "https://user:[email protected]/path/
f = urllib2.urlopen(url)
print f.read()

gives:

给出:

httplib.InvalidURL: nonnumeric port: '[email protected]'

回答by John Giotta

This has never failed me

这从来没有让我失望

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

回答by S.Lott

Please read about the urllib2 password manager and the basic authentication handler as well as the digest authentication handler.

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

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

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

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

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

Your urllib2 script must actually provide enough information to do HTTP authentication. Usernames, Passwords, Domains, etc.

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

回答by Dave Webb

If you want to pass username and password information to urllib2you'll need to use an HTTPBasicAuthHandler.

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

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

这是一个教程,向您展示如何做到这一点。

回答by Johannes Charra

You cannot pass credentials to urllib2.openlike that. In your case, useris interpreted as the domain name, while [email protected]is interpreted as the port number.

你不能urllib2.open像那样传递凭据。在您的情况下,user被解释为域名,而[email protected]被解释为端口号。