How can I avoid exceptions from urllib.request.urlopen
if response.status_code
is not 200? Now it raise URLError
or HTTPError
based on request status.
Is there any other way to make request with python3 basic libs?
How can I get response headers if status_code != 200
?
Use try except
, the below code:
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request("http://www.111cn.net /")
try:
response = urlopen(req)
except HTTPError as e:
# do something
print('Error code: ', e.code)
except URLError as e:
# do something
print('Reason: ', e.reason)
else:
# do something
print('good!')