Categories
Programming

Python requests get status code

In this article, we will provide code examples on how you can get the status code of a page via the Python requests module.

Python requests get status code

The python requests module is straight forward in it’s usage, with just 3 simple lines, you can get a status code from any page.

The python requests get status code

import requests
myrequest = requests.get('https://cyberwarzone.com')
print myrequest.status_code

The code above will print the status code of the cyberwarzone website. Now to make it more fun, you can also start using the status codes to perform specific tasks. Just add an if statement for the status code.

Answer status code of cyberwarzone.com
import requests
myrequest = requests.get('http://cyberwarzone.com')
statuscode = myrequest.status_code
if statuscode == 500: ##Internal Server Error
print "You made a huge mistake on the server"
if statuscode == 200: ## OK
print "Get yourself some coffee"

The code above, will print out ‘You made a huge mistake on the server”, if the 500 internal server error status code is returned. This can be used by system administrators to keep track of their page via a simple Python script.

If the status code is 200, then everything is oke. The script will print out ‘Get yourself some coffee” if the status code returned is 200.

You can get a list of all the status codes via IETF.org.

By CWZ

Founder of Cyberwarzone.com.