Wednesday, 2 September 2020

Python 3: Basic Test for Web Site Availability

  In Python 3, doing a basic test for web site availability is very straightforward:

  • >>> import urllib.request
  • >>> print(urllib.request.urlopen("https://www.cosonok.com").getcode())
  • 200
  • >>>

It needs a little modification so you don't get an ugly error if the website is not available:

  • >>> try:
  • ...     a = urllib.request.urlopen("https://www.cosonok.co").getcode()
  • ...     print("OK (" + str(a) + ")")
  • ... except urllib.error.URLError: print("FAILED")
  • ...
  • FAILED
  • >>>

What if we want colors?

The below shows you how to install termcolor in the command prompt. There are two methods: 1) for if 'pip download' works for you, and 2) if you have to get the file manually from one machine to install on another machine. Because I am running Python on a Windows machine, we also need to get colorama. Windows cmd doesn't support ANSI coding like linux/unix which termcolor uses (perhaps termcolor is surplus to requirements with Windows cmd...)

Method 1:

  • > python -m pip install termcolor
  • > python -m pip install colorama

Method 2:

  • python -m pip download termcolor
  • python -m pip install termcolor-1.1.0.tar.gz
  • pythom -m pip download colorama
  • python -m pip install colorama-0.4.3-py2.py3-none-any.whl

Note: See https://pypi.org/project/termcolor/ for more on termcolor.

A modified Python script using colors - save this as say webCheck.py:

  • import sys
  • from termcolor import *
  • import colorama
  • colorama.init()
  • import urllib.request

  • url = "https://www.cosonok.com"
  • try:
  •     status_code = urllib.request.urlopen(url).getcode()
  •     cprint(("OK(" + str(status_code) + ")"),'white','on_green')
  • except urllib.error.URLError:
  • cprint("FAILED",'white','on_red')

Image: Example running webCheck.py


A very sinple example. To be enhanced in a future post...

2 comments:

  1. The features an engaged staff that prioritizes customer involvement and satisfaction. user experience company are responsive and genuine—an ideal partner.

    ReplyDelete