通过代理使用基本认证的Python HTTPS客户端

3 投票
3 回答
4541 浏览
提问于 2025-04-15 14:28

我想用Python从一个网站获取内容,这个网站是通过HTTPS协议,并且需要基本的身份验证。我需要把内容保存到硬盘上。我是在一个内部网络中,信任这个HTTPS服务器。我的平台是Windows,Python版本是2.6.2。

我尝试过使用urllib2这个库,但到目前为止还没有成功。

我现在有一个解决方案,是通过os.system()来调用wget命令:

wget_cmd = r'\path\to\wget.exe -q -e "https_proxy = http://fqdn.to.proxy:port" --no-check-certificate --http-user="username" --http-password="password" -O path\to\output https://fqdn.to.site/content'

我想摆脱os.system()这个方法。在Python中可以做到吗?

3 个回答

0

你也可以试试这个链接:http://code.google.com/p/python-httpclient/

(它还支持验证服务器的证书哦。)

3

试试这个(注意你需要填写你服务器的领域信息):

import urllib2
authinfo = urllib2.HTTPBasicAuthHandler()
authinfo.add_password(realm='Fill In Realm Here',
                      uri='https://fqdn.to.site/content',
                      user='username',
                      passwd='password')
proxy_support = urllib2.ProxyHandler({"https" : "http://fqdn.to.proxy:port"})
opener = urllib2.build_opener(proxy_support, authinfo)
fp = opener.open("https://fqdn.to.site/content")
open(r"path\to\output", "wb").write(fp.read())
3

很长一段时间以来,使用urllib2时,代理和https都无法正常工作,这个问题一直存在。这个问题将在下一个发布的Python 2.6版本(v2.6.3)中修复。

在此之前,你可以自己重新实现正确的支持,这就是我们为Mercurial所做的:http://hg.intevation.org/mercurial/crew/rev/59acb9c7d90f

撰写回答