使用Python的请求模块识别并打破异常:“ OpenSSL.SSL.Error”

时间:2019-07-01 13:48:33

标签: python python-3.x openssl python-requests

我目前正在解析URL列表,如果一个URL抛出异常,我只想中断并转到下一个URL。

但是,我不断得到

OpenSSL.SSL.Error: [('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')]

现在解决此异常超出了我的专业知识,所以我希望现在能够跳过它并稍后再处理。但是,我的问题是,当我编写try catch来这样做时:

    try:
        r = requests_retry_session(session=s).get(test_link, verify=cafile, allow_redirects=True, timeout=4.0)

    except OpenSSL.SSL.Error:
        print('SSL error, moving to next domain')
        break

我明白了:

NameError: name 'OpenSSL' is not defined

我知道解决此问题的最简单方法是只做verify=False,但这非常不安全,我宁愿不接受可能的MITM攻击。

我尝试过的事情:

尝试follow the documentation of this previous related question

pip install --upgrade certifi

最后是一个非常草率的try catch块,它实际上捕获了NameError: name 'OpenSSL' is not defined并将其作为名称错误中断,这根本不是pythonic。我知道我可以全面掌握所有内容,但是,我不想跳过所有错误。

我正在运行python 3.7.3,并请求2.22.0

2 个答案:

答案 0 :(得分:1)

  

尝试follow the documentation of this previous related question

您应该按照以下说明解决此异常处理,并安装pyopensslpip install pyopenssl)并将其OpenSSL导入模块顶部。

答案 1 :(得分:1)

找到了正确的异常,它的琐碎却令人困惑的文档。

因此,OpenSSL.SSL.Error将通过使用requests.exceptions.SSLError被捕获,在这种情况下,无需(明确地)导入OpenSSL或pyOpenSSL。