Shawn Shawn - 4 months ago 26
Python Question

python capture URLError code

I want to use Python to monitor a website that uses HTTPS.
The problem is that the certificate on the website is invalid.
I don't care about that, I just want to know that the website is running.

My working code looks like this:

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


that ends in URLError being called. The error code is 645.

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


So, I'm trying to except code 645 as OK. I've tried this:

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


but get this error:

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


how do I add this exception?

Answer

Please have a look at the great requests package. It will simplify your life when doing http communication. See http://requests.readthedocs.io/en/master/.

pip install requests

To skip certificate check, you would do something like this (note the verify parameter!):

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

See the full documentation here.

HTH