2016-08-04 38 views
0

我想用Python来监视使用HTTPS的网站。 问题是,网站上的证书无效。 我不在乎,我只是想知道网站正在运行。python capture URLError code

我工作的代码如下所示:

from urllib.request import Request, urlopen 
from urllib.error import URLError, HTTPError 
req = Request("https://somedomain.com") 

try: 
    response = urlopen(req) 
except HTTPError as e: 
    print('server couldn\'t fulfill the request') 
    print('error code: ', e.code) 
except URLError as e: 
     print(e.args)  
else: 
    print ('website ok') 

,在URLError结束被调用。错误代码是645.

C:\python>python monitor443.py 
(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645)'),) 

所以,我试图除了代码645以外。我已经试过这样:

from urllib.request import Request, urlopen 
from urllib.error import URLError, HTTPError 
req = Request("https://somedomain.com") 

try: 
    response = urlopen(req) 
except HTTPError as e: 
    print('server couldn\'t fulfill the request') 
    print('error code: ', e.code) 
except URLError as e: 
     if e.code == 645: 
      print("ok") 
     print(e.args)  
else: 
    print ('website ok') 

,但得到这个错误:

Traceback (most recent call last): 
    File "monitor443.py", line 11, in <module> 
    if e.code == 645: 
AttributeError: 'URLError' object has no attribute 'code' 

如何添加此异常?

+0

['URLError'是OSERROR的一个子类(http://stackoverflow.com/q/38773209/344286)可能会说,它是在['e.errno'发现](https://docs.python.org/3/library/exceptions.html#OSError.errno)? –

+0

e.errno返回“none” – Shawn

+0

另外... 645不是errorno,那是错误发生的C源代码行,AFAIK。 –

回答

1

请看看伟大的requests包。这会在进行http通信时简化您的生活。见http://requests.readthedocs.io/en/master/

pip install requests 

要跳过证书检查,你会做这样的事情(注意verify参数!):

requests.get('https://kennethreitz.com', verify=False) 
<Response [200]> 

查看完整的文档here

HTH

1

我无法安装SLL库(egg_info错误)。 这是我最后做

from urllib.request import Request, urlopen 
from urllib.error import URLError, HTTPError 

def sendEmail(r):  
    #send notification 
    print('send notify') 

req = Request("https://somedomain.com") 

try: 
    response = urlopen(req) 
except HTTPError as e: 
    print('server couldn\'t fulfill the request') 
    print('error code: ', e.code) 
    sendEmail('server couldn\'t fulfill the request') 
except URLError as e: 
     theReason=str(e.reason) 
     #[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:645) 
     if theReason.find('CERTIFICATE_VERIFY_FAILED') == -1: 
      sendEmail(theReason) 
     else: 
      print('website ok')   
else: 
    print('website ok')