2016-08-04 8 views
0

私は、HTTPSを使用するウェブサイトを監視するためにPythonを使いたいと思っています。 問題は、Webサイトの証明書が無効であることです。 私はそれについて気にしない、私はちょうどウェブサイトが実行されていることを知りたい。PythonのキャプチャURLエラーコード

私の作業コードは次のようになります。URLErrorで終わる

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') 

が呼び出されます。エラーコードは、私がコード645としてOKを除く外しようとしている、だから、645

C:\python>python monitor443.py 
(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c: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') 
関連する問題