我想用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'
如何添加此異常?
['URLError'是OSERROR的一個子類(http://stackoverflow.com/q/38773209/344286)可能會說,它是在['e.errno'發現](https://docs.python.org/3/library/exceptions.html#OSError.errno)? –
e.errno返回「none」 – Shawn
另外... 645不是errorno,那是錯誤發生的C源代碼行,AFAIK。 –