捕获除SSL问题的请求外

时间:2019-09-11 15:29:46

标签: python python-3.x

当我向expired.badssl.com发送HEAD请求以测试脚本如何响应时,出现以下错误:

HTTPSConnectionPool(host='expired.badssl.com', port=443): Max retries exceeded with url: / (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)'),))

我可以专门捕获SSLError以便知道它是错误的SSL吗?

我需要将此部分分配给except中的CERTIFICATE_VERIFY_FAILED[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:852)中的变量

我的要求:

host = "https://expired.badssl.com/"
timeout = 5

try:
    r = requests.head(host, headers=headers, timeout=timeout)

    try:
        print ('Status', r.status_code)
        print ('Headers', r.headers)

    except NameError:
        print("Undefined variable")

except requests.exceptions.Timeout:
    print ('Timeout...')

except requests.exceptions.TooManyRedirects:
    print ('Bad URL...')

except requests.exceptions.RequestException as e:
    print (e)

2 个答案:

答案 0 :(得分:2)

您可以通过异常参数来获取它:

import requests

try:
    r = requests.head("https://expired.badssl.com/", timeout=5)

    try:
        print ('Status', r.status_code)
        print ('Headers', r.headers)

    except NameError:
        print("Undefined variable")

except requests.exceptions.SSLError as ssl_error:
    print(ssl_error)
    inner_exception = ssl_error.args[0]
    inner_ssl_error = inner_exception.reason.args[0]
    print(type(inner_ssl_error))
    for key, value in vars(inner_ssl_error).items():
        print(key, '=', value)
    # or just inner_ssl_error.reason etc.

答案 1 :(得分:0)

测试以下代码

import requests 

host = "https://expired.badssl.com/";
timeout = 5
try:
    r = requests.head(host)


    try:
        print ('Status', r.status_code)
        print ('Headers', r.headers)

    except NameError:
        print("Undefined variable")
except requests.exceptions.Timeout:
    print ('Timeout...')
except requests.exceptions.TooManyRedirects:
    print ('Bad URL...')
except requests.exceptions.SSLError:
    print('certificate verify failed')
except requests.exceptions.RequestException as e:
    print (e)

OR

import requests
class check_link:
  def check_broken_link(self,data):
    try:
      r = requests.head(data)                 
      try:
                print ('Status', r.status_code)
                print ('Headers', r.headers)

      except NameError:
          return ("UNDEFINED")

    except requests.exceptions.SSLError:
        return "CERTIFICATE_VERIFY_FAILED"

qc=check_link()
result =qc.check_broken_link('https://expired.badssl.com/')
print(result)