I'm using the Requests library and accessing a website to gather data from it with the following code:
r = requests.get(url)
I want to add error testing for when an improper URL is entered and a 404 error is returned. If I intentionally enter an invalid URL, when I do this:
print r
I get this:
<Response [404]>
EDIT:
I want to know how to test for that. The object type is still the same. When I do r.content
or r.text
, I simply get the HTML of a custom 404 page.
Look at the
r.status_code
attribute:Demo:
If you want
requests
to raise an exception for error codes (4xx or 5xx), callr.raise_for_status()
:You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:
If you want to be more explicit, use
if r.ok:
.