python请求异常-不断抛出错误

收到HTTP 200时,脚本运行正常。但是,一旦出现异常,我就会收到错误消息。我知道该网站未安装有效的SSL证书,并且我尝试过request.exceptions.RequestException来捕获任何内容,但仍会引发错误。我还会不时出现诸如代理错误之类的异常,而requests.exceptions.RequestException不会捕获该异常。我也尝试过在try下:request.raise_for_status(),但仍然抛出错误。代码如下:


def verify_ssl(proxy_info, target): 

   print('Attempting to verify SSL Cert on %s:443' % target)

   if proxy_info == None:

      response = requests.get('https://%s' % target)

   if proxy_info != None:

      response = requests.get('https://%s' % target, proxies=proxy_info)

   try:

      response

   except requests.exceptions.SSLError as g:

      print('SSL Verification Error %s' % g)

   return ('Successfully Verified SSL Cert: HTTP 200 received.\n')

调试给我这个:


    Traceback (most recent call last):

  File "c:\Users\appleta\Desktop\ping.py", line 69, in <module>

    ssl_result = verify_ssl(proxy_info, target)

  File "c:\Users\appleta\Desktop\ping.py", line 37, in verify_ssl

    response = requests.get('https://%s' % target)

  File "C:\Python34\lib\site-packages\requests\api.py", line 72, in get

    return request('get', url, params=params, **kwargs)

  File "C:\Python34\lib\site-packages\requests\api.py", line 58, in request

    return session.request(method=method, url=url, **kwargs)

  File "C:\Python34\lib\site-packages\requests\sessions.py", line 512, in request

    resp = self.send(prep, **send_kwargs)

  File "C:\Python34\lib\site-packages\requests\sessions.py", line 622, in send

    r = adapter.send(request, **kwargs)

  File "C:\Python34\lib\site-packages\requests\adapters.py", line 511, in send

    raise SSLError(e, request=request)

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


qq_遁去的一_1
浏览 184回答 1
1回答

慕斯709654

在python中的表达式:response可从来没有产生异常。您必须将两个get调用都放在try块中:def verify_ssl(proxy_info, target):&nbsp;&nbsp; &nbsp;print('Attempting to verify SSL Cert on %s:443' % target)&nbsp; &nbsp;try:&nbsp; &nbsp; &nbsp; &nbsp;if proxy_info is None:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; response = requests.get('https://%s' % target)&nbsp; &nbsp; &nbsp; &nbsp;else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; response = requests.get('https://%s' % target, proxies=proxy_info)&nbsp; &nbsp;except requests.exceptions.SSLError as g:&nbsp; &nbsp; &nbsp; print('SSL Verification Error %s' % g)&nbsp; &nbsp; &nbsp; return 'Got SSL error'&nbsp; &nbsp;return 'Successfully Verified SSL Cert: HTTP 200 received.\n'另外:请注意,您总是返回字符串,Successfully Verified SSL Cert ...因为即使发生错误,您也只打印错误消息,然后恢复执行。您可能想在except块中返回不同的内容。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python