Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Test the given page is found or not on the server Using Python

  • Last Updated : 21 Aug, 2021

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.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :