Handling problems
Status codes help us to see whether our response was successful or not. Any code in the 200 range indicates a success, whereas any code in either the 400 range or the 500 range indicates failure.
Status codes should always be checked so that our program can respond appropriately if something goes wrong. The urllib
package helps us in checking the status codes by raising an exception if it encounters a problem.
Let's go through how to catch these and handle them usefully. For this try the following command block:
>>> import urllib.error >>> from urllib.request import urlopen >>> try: ... urlopen('http://www.ietf.org/rfc/rfc0.txt') ... except urllib.error.HTTPError as e: ... print('status', e.code) ... print('reason', e.reason) ... print('url', e.url) ... status: 404 reason: Not Found url: http://www.ietf.org/rfc/rfc0.txt
Here we've requested RFC 0, which doesn't exist. So the server has...