Saturday, November 16, 2024
Google search engine
HomeLanguagesTest the given page is found or not on the server Using...

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 module
from urllib.request import urlopen
from urllib.error import *
 
# try block to read URL
try:
    html = urlopen("https://www.geeksforgeeks.org/")
     
# except block to catch
# exception
# and identify error
except 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 module
import requests
 
# create a function
# pass the url
def 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 code
url_ok(url)


Output:

True

RELATED ARTICLES

Most Popular

Recent Comments