256 Kilobytes

Answers in Web Scraping, Data Analysis | By August R. Garcia

Published

313 views, 0 RAMs, and 1 comment

Tags: Python, Web Crawling, Termcolor

Profile Photo - August R. GarciaAugust R. GarciaLARPing as a Sysadmi...Portland, ORSite Owner

The easiest way to do this is with the Termcolor Python library. If not already installed, run:

  • sudo pip install termcolor

And then the following function should work correctly.

from termcolor import colored

def colorize_status_code(status_code):
        if   ( status_code >= 500 ):  return colored(status_code, "red"   , attrs=['bold']) 
        elif ( status_code >= 400 ):  return colored(status_code, "yellow", attrs=['bold']) 
        elif ( status_code >= 300 ):  return colored(status_code, "blue"  , attrs=['bold']) 
        elif ( status_code >= 200 ):  return colored(status_code, "green" , attrs=['bold']) 
        else:                         return colored(status_code, "grey"  , attrs=['bold']) 

# Generic Usage
print colorize_status_code( 503 )
print colorize_status_code( 404 )
print colorize_status_code( 301 )
print colorize_status_code( 200 )
print colorize_status_code( 102 )

# Realer Example
import requests
r = requests.get("https://www.example.com")
print colorize_status_code( r.status_code )

If you want to add the written status codes as well, you can use this version of the code:

import httplib
from termcolor import colored

def colorize_status_code(status_code, with_msg=False):
        msg = ""
        if   (with_msg == True):
                try:      msg = " " + httplib.responses[status_code]
                except:   msg = " " + "Unknown HTTP Status Code"

        if   ( status_code >= 500 ):  return colored( str(status_code)+msg, "red"   , attrs=['bold'])
        elif ( status_code >= 400 ):  return colored( str(status_code)+msg, "yellow", attrs=['bold'])
        elif ( status_code >= 300 ):  return colored( str(status_code)+msg, "blue"  , attrs=['bold'])
        elif ( status_code >= 200 ):  return colored( str(status_code)+msg, "green" , attrs=['bold'])
        else:                         return colored( str(status_code)+msg, "grey"  , attrs=['bold'])

# Examples. The with_msg parameter can be omitted and will be false by default.
print colorize_status_code( 503 )
print colorize_status_code( 404 )
print colorize_status_code( 301, True )
print colorize_status_code( 200, True )
print colorize_status_code( 102, True )

Some lesser-used HTTP status codes seem to not be listed in the httplib.responses array, which are then caught by the try/catch statement. These are the codes that seem to exist:

  • 100 Continue
  • 101 Switching Protocols
  • 200 OK
  • 201 Created
  • 202 Accepted
  • 203 Non-Authoritative Information
  • 204 No Content
  • 205 Reset Content
  • 206 Partial Content
  • 300 Multiple Choices
  • 301 Moved Permanently
  • 302 Found
  • 303 See Other
  • 304 Not Modified
  • 305 Use Proxy
  • 306 (Unused)
  • 307 Temporary Redirect
  • 400 Bad Request
  • 401 Unauthorized
  • 402 Payment Required
  • 403 Forbidden
  • 404 Not Found
  • 405 Method Not Allowed
  • 406 Not Acceptable
  • 407 Proxy Authentication Required
  • 408 Request Timeout
  • 409 Conflict
  • 410 Gone
  • 411 Length Required
  • 412 Precondition Failed
  • 413 Request Entity Too Large
  • 414 Request-URI Too Long
  • 415 Unsupported Media Type
  • 416 Requested Range Not Satisfiable
  • 417 Expectation Failed
  • 500 Internal Server Error
  • 501 Not Implemented
  • 502 Bad Gateway
  • 503 Service Unavailable
  • 504 Gateway Timeout
  • 505 HTTP Version Not Supported

The Termcolor Python library also has a parameter to set a background color and there are other attributes that can be set as well. Also see this list of HTTP status codes.

Also, if you want to do this without a library, there are ANSI escape sequencies that can be used for text coloring.

Download more RAM. 🐏 ⨉ 0Posted by August R. Garcia 10 months ago 🕓 Posted at 29 July, 2019 22:34 PM PDT

Sir, I can do you a nice SEO.

Profile Photo - August R. GarciaAugust R. GarciaLARPing as a Sysadmi...Portland, ORSite Owner

For Python 3:

import http.client 
[...]
                try:      msg = " " + http.client.responses[status_code]
[...]

Code is basically the same, but the library name has changed. Also, the Python 3 library seems to have better coverage for error messages.

Download more RAM. 🐏 ⨉ 0Posted by August R. Garcia 8 months ago 🕓 Posted at 09 September, 2019 12:10 PM PDT

Sir, I can do you a nice SEO.

Post a New Comment

Do you like having a good time?

Register an Account

You can also login to an existing account or reset your password. All use of this site is subject to the terms of service and privacy policy.

Read Quality Articles

Read some quality articles. If you can manage to not get banned for like five minutes, you can even post your own articles.

View Articles →

Argue with People on the Internet

Use your account to explain why people are wrong on the Internet forum.

View Forum →

Vandalize the Wiki

Or don't. I'm not your dad.

View Wiki →

Ask and/or Answer Questions

If someone asks a terrible question, post a LMGTFY link.

View Answers →

Make Some Money

Hire freelancers and/or advertise your goods and/or services. Hire people directly. We're not a middleman or your dad. Manage your own business transactions.

Register an Account

Answers— Read More

Find more related content below!