Python 3 urllib.request.urlopen

Bogdan Ruzhitskiy picture Bogdan Ruzhitskiy · Apr 9, 2015 · Viewed 26.6k times · Source

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 ?

Answer

thinkerou picture thinkerou · Apr 9, 2015

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