Test the given page is found or not on the server Using Python
In this article, we are going to write a Python script to test the given page is found or not on the server. We will see various methods to do the same.
Method 1: Using Urllib.
Urllib is a package that allows you to access the webpage with the program.
Installation:
pip install urllib
Approach:
- Import module
- Pass the URL in urllib.request() reading URLs
- Now check with urllib.error containing the exceptions raised by urllib.request
Implementation:
Python3
# import modulefrom urllib.request import urlopenfrom urllib.error import *# try block to read URLtry: # except block to catch# exception# and identify errorexcept HTTPError as e: print("HTTP error", e) except URLError as e: print("Opps ! Page not found!", e)else: print('Yeah ! found ') |
Output:
Yeah ! found
Method 2: Using requests
Request allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal.
Installation:
pip install requests
Approach:
- Import module
- Pass the Url into requests.head()
- If response.status_code == 200 then server is up
- if response.status_code == 404 then server in down
Implementation:
Python3
# import moduleimport requests# create a function# pass the urldef url_ok(url): # exception block try: # pass the url into # request.hear response = requests.head(url) # check the status code if response.status_code == 200: return True else: return False except requests.ConnectionError as e: return e# driven codeurl_ok(url) |
Output:
True





Please Login to comment...