check if string is url python code example

Example 1: check if string is url python

#USE requests.get() TO CHECK IF A STRING IS A URL

try:
    response = requests.get("http://www.avalidurl.com/")
    print("URL is valid and exists on the internet")
except requests.ConnectionError as exception:
    print("URL does not exist on Internet")
OUTPUT
URL does not exist on Internet


#URLValidator() ensures a value looks like a URL, 
#but does not check if the URL exists on the internet. 
#To check if the URL exists on the internet, call requests.get(url) 
#in a try-statement to make a GET request from the source url and return a 
#Response object containing the server's response to the request. 
#If the URL does not exist on the internet, it raises a ConnectionError and 
#the program continues to the except-statement.

Example 2: python check if string is url

from django.core.validators import URLValidator()
validate = URLValidator()

try:
    validate("http://www.avalidurl.com/")
    print("String is a valid URL")
except ValidationError as exception:
    print("String is not valid URL")