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
from urllib.request import urlopen
from urllib.error import *
try :
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 requests
def url_ok(url):
try :
response = requests.head(url)
if response.status_code = = 200 :
return True
else :
return False
except requests.ConnectionError as e:
return e
url_ok(url)
|
Output:
True
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
21 Aug, 2021
Like Article
Save Article