【问题标题】:Identifying and breaking on exception: 'OpenSSL.SSL.Error' using python's requests module识别和打破异常:'OpenSSL.SSL.Error'使用python的请求模块
【发布时间】:2019-07-01 13:48:33
【问题描述】:

我目前正在解析一个 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

【问题讨论】:

  • 你能告诉我你想访问哪个网站吗?
  • NameError: name 'OpenSSL' is not defined - 你还记得import OpenSSL吗? ;) 此外,如果您将每个请求作为线程运行,异常只会终止线程,您可以轻松丢弃终止的结果。
  • @h4z3 现在运行它,我已经能够在遇到错误之前解析几个域,所以我不会想象(我认为?)这将是问题。
  • @LucasWieloch 我再次运行它以获取它是哪个域,这需要一秒钟。更新:这是域4mresearch.com

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


【解决方案1】:

正在尝试follow the documentation of this previous related question

您应该按照这些说明并安装 pyopenssl (pip install pyopenssl) 并在模块顶部导入其 OpenSSL 来解决此异常处理。

【讨论】:

  • 我编辑了我的答案,它是关于处理异常的,我们没有足够的数据来处理实际的错误。
【解决方案2】:

找到正确的异常,它的文档极其琐碎但令人困惑。

所以OpenSSL.SSL.Error 将被使用requests.exceptions.SSLError 捕获,并且在这种情况下不需要(显式地)导入OpenSSL 或pyOpenSSL。

【讨论】:

  • 是的,我看不出有一个整洁的方法来处理这个问题。当我调用 load_certificate 时抛出异常,我无法使用 OpenSSL.SSL.Error 捕获它。
猜你喜欢
  • 2018-09-26
  • 2012-06-19
  • 2016-08-10
  • 1970-01-01
  • 1970-01-01
  • 2011-08-31
  • 1970-01-01
  • 2018-04-30
  • 1970-01-01
相关资源
最近更新 更多