捕获 SSL 问题的请求除外

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


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_FAILEDfrom[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)


侃侃尔雅
浏览 105回答 2
2回答

PIPIONE

您可以通过异常参数获取它:import requeststry:    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.

芜湖不芜

测试下面的代码import requests host = "https://expired.badssl.com/";timeout = 5try:    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)或者import requestsclass 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)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python