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

发布于 2024-08-15 11:56:43 字数 501 浏览 3 评论 0原文

如何在 Python 中打开 https url?

import urllib2

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

给出:

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

How do you open https url in Python?

import urllib2

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

gives:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

染墨丶若流云 2024-08-22 11:56:43

这从来没有让我失望过

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

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
花之痕靓丽 2024-08-22 11:56:43

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

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

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

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

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

http://docs.python.org/library/urllib2.html#abstractbasicauthhandler-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.

匿名。 2024-08-22 11:56:43

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

这是一个向您展示如何操作的教程。

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

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

冷…雨湿花 2024-08-22 11:56:43

您无法像这样将凭据传递给 urllib2.open。在您的情况下, user 被解释为域名,而 [email protected] 被解释为端口号。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文