【问题标题】:python requests exception - keeps throwing errorspython请求异常 - 不断抛出错误
【发布时间】:2018-08-14 15:00:46
【问题描述】:

脚本在收到 HTTP 200 时工作正常。但是,一旦我收到异常,我就会收到错误消息。我知道该网站没有安装有效的 SSL 证书,并且我尝试使用 requests.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)'),))

【问题讨论】:

    标签: python python-requests


    【解决方案1】:

    在python中的表达式:

    response
    

    不能从不产生异常。您必须将两个 get 调用都放在 try 块内:

    def verify_ssl(proxy_info, target): 
       print('Attempting to verify SSL Cert on %s:443' % target)
       try:
           if proxy_info is None:
              response = requests.get('https://%s' % target)
           else:
              response = requests.get('https://%s' % target, proxies=proxy_info)
       except requests.exceptions.SSLError as g:
          print('SSL Verification Error %s' % g)
          return 'Got SSL error'
       return 'Successfully Verified SSL Cert: HTTP 200 received.\n'
    

    另外:请注意,您总是返回字符串Successfully Verified SSL Cert ...,因为即使出现错误,您也只会打印错误消息,然后继续执行。您可能希望在 except 块中返回不同的内容。

    【讨论】:

    • 很棒的贾科莫,非常感谢你。我假设当我指定对 request.get 的响应时,它会在 try 命令中提取它,所以我什至不认为这可能是问题所在。 :)
    猜你喜欢
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多