我有使用 urllib2 模块下载 https 页面时遇到问题 https://stackoverflow.com/questions/33264502/windowserror-error-5-access-is-denied-using-urllib2,这似乎是由于 urllib2 无法访问系统的证书存储造成的。
为了解决这个问题,一种可能的解决方案是使用 certifi 模块,使用 pycurl 下载 https 网页。以下是这样做的示例:
def download_web_page_with_curl(url_website):
from pycurl import Curl, CAINFO, URL
from certifi import where
from cStringIO import StringIO
response = StringIO()
curl = Curl()
curl.setopt(CAINFO, where())
curl.setopt(URL, url_website)
curl.setopt(curl.WRITEFUNCTION, response.write)
curl.perform()
curl.close()
return response.getvalue()
有没有办法将 certifi 与 urllib2 一起使用(以与上面的 pycurl 示例相当的方式),这将允许我下载 https 站点?或者,是否有另一种可行的基于 urllib2 的解决方法可以在不影响安全性的情况下解决权限问题?
建议根据我的其他答案使用请求。但是,要回答如何使用 urllib2 执行此操作的原始问题:
import urllib2
import certifi
def download_web_page_with_urllib2(url_website):
t = urllib2.urlopen(url_website, cafile=certifi.where())
return t.read()
text = download_web_page_with_urllib2('https://www.google.com/')
关于错误检查的相同建议也适用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)