在 urllib2 中使用 certifi 模块? [英] Using certifi module with urllib2?

查看:26
本文介绍了在 urllib2 中使用 certifi 模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 urllib2 模块下载 https 页面时遇到问题,这似乎是由于 urllib2 无法访问系统的证书存储所致.

I'm having trouble downloading https pages with the urllib2 module, which seems to result from urllib2's inability to access the system's certificate store.

要解决此问题,一种可能的解决方案是使用 certifi 模块下载带有 pycurl 的 https 网页.以下是这样做的示例:

To get around this issue, one possible solution is to download https web pages with pycurl, by using the certifi module. The following is an example of doing so:

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 的解决方法可以在不影响安全性的情况下解决权限问题?

Is there a way to use certifi with urllib2 (in a fashion comparable to the pycurl example above), which will permit me to download https sites? Alternatively, is there another feasible urllib2-based workaround which will remedy the permissions issue, without compromising security?

推荐答案

建议根据我的其他答案使用请求.但是,要回答有关如何使用 urllib2 执行此操作的原始问题:

Would recommend using requests per my other answer. However, to answer the original question of how to do this with 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/')

同样适用于错误检查的建议.

The same recommendations about error checking apply.

这篇关于在 urllib2 中使用 certifi 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆