Prerequisite: Python Urllib module
In this article, we are going to write scripts to test whether the given page is found on the server or not with a GUI application. We need to Install Urllib Module to carry out this operation. Type this command in your terminal.
pip install urllib
Approach:
- Import urllib module.
- Read URL with urllib.request.urlopen().
- Check if Read URL gives any exception.
Implementation:
Python3
# import module from urllib.request import urlopen, URLError, HTTPError Â
# exception handling to # catch URL error try : Â
except URLError as e: Â Â Â Â print ( "Server not found!" ) Â
except HTTPError as e: Â Â Â Â print ( "HTTP error" ) Â
else : Â Â Â Â print ( "Server found" ) |
Output:
Server found
Application to test the given page is found or not on the server with Tkinter: This Script combines the implementation above with a GUI.
Python3
# import modules from tkinter import * from urllib.request import urlopen, URLError Â
# user defined function def URL_check(): Â Â Â Â try : Â Â Â Â Â Â Â Â html = urlopen( str (e1.get())) Â Â Â Â except URLError as e: Â Â Â Â Â Â Â Â res = "Server not found!" Â Â Â Â else : Â Â Â Â Â Â Â Â res = "Server found" Â Â Â Â result. set (res) Â
Â
# object of tkinter # and background set to light grey master = Tk() master.configure(bg = 'light grey' ) Â
# Variable Classes in tkinter result = StringVar() Â
Â
# Creating label for each information Â
# name using widget Label Label(master, text = "Enter URL : " , bg = "light grey" ).grid(row = 1 , sticky = W) Label(master, text = "Status :" , bg = "light grey" ).grid(row = 3 , sticky = W) Â
# Creating label for class variable Â
# name using widget Entry Label(master, text = "", textvariable = result, Â Â Â Â Â Â bg = "light grey" ).grid(row = 3 , column = 1 , sticky = W) Â
Â
e1 = Entry(master, width = 50 ) e1.grid(row = 1 , column = 1 ) Â
# creating a button using the widget b = Button(master, text = "Check" , command = URL_check, bg = "white" ) b.grid(row = 1 , column = 2 , columnspan = 2 , rowspan = 2 , padx = 5 , pady = 5 ,) Â
mainloop() |
Output:
Check another URL.