How to find if a string is a valid URL or not in Python

How to find if a string is a valid URL or not in Python :

It is always a good idea to check if a string or url is valid or not before trying to make a request. The request will fail anyway but if we test it before that, we can always avoid that failure.

In python, we can easily find out if a url is valid or not. In this post, I will show you how to do that with examples.

validator module:

validators is a python module that provides different types of validation methods. Using this module, we can validate different types of inputs in Python.

For validating an url, we can use the url method. This method is defined as below:

def url(value, public=False)

It takes the url as value. If the url is valid, it returns True, else it will throw one ValidationFailure. public is set to True for public IP address.

Installation:

validators can be installed via pip. You can use pip or pip3 to install it:

pip3 install validators

Sample programs:

The below program shows it how it behaves with a valid url:

import validators

isValid = validators.url("https://codevscolor.com")

if isValid == True:
    print("Valid url")
else:
    print("Invalid url")

It will print:

Valid url

And for a invalid url:

import validators

isValid = validators.url("httpz://codevscolor.com")

if isValid == True:
    print("Valid url")
else:
    print("Invalid url")

It will print:

Invalid url

You might also like: