Inquiries - how to find out if you get 404

I use the Requests library and access the website to collect data from it using the following code:

r = requests.get(url) 

I want to add error checking when the wrong URL is entered and the 404 error is returned. If I intentionally enter the wrong URL when I do this:

 print r 

I get this:

 <Response [404]> 

EDIT:

I want to know how to verify this. The type of object is still the same. When I do r.content or r.text , I just get the 404 user page HTML code.

+46
python python-requests
Mar 06 '13 at 21:46
source share
1 answer

Look at the r.status_code attribute:

 if r.status_code == 404: # A 404 was issued. 

Demo:

 >>> import requests >>> r = requests.get('http://httpbin.org/status/404') >>> r.status_code 404 

If you want requests to throw an exception for error codes (4xx or 5xx), call r.raise_for_status() :

 >>> r = requests.get('http://httpbin.org/status/404') >>> r.raise_for_status() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "requests/models.py", line 664, in raise_for_status raise http_error requests.exceptions.HTTPError: 404 Client Error: NOT FOUND >>> r = requests.get('http://httpbin.org/status/200') >>> r.raise_for_status() >>> # no exception raised. 
+102
Mar 06 '13 at 21:48
source share



All Articles