Check if a string is a valid URL or not in Python

Hello programmers, in this post we will learn how to Check if a string is a valid URL or not in Python.

Python provides different modules that make it easy to write code in comparison to any other language like C. Something while writing complex code there may be a situation when we have to validate a URL(Uniform Resource Locator)  or a string passed that it is URL or not.

So stay with us to learn such amazing Python programming tricks.

Also read: How to get the IP address of a URL in Python

Python program to check if a string is a valid URL or not 

Prerequisites: Install the validators module in Python using the command pip install validators.

To check whether the string entered is a valid URL or not we use the validators module in Python. When we pass the string to the method url()  present in the module it returns true(if the string is URL) and ValidationFailure(func=url, …)  if URL is invalid.

Here is the code to validate a URL in Python.

import validators
valid=validators.url('https://codespeedy.com/')
if valid==True:
    print("Url is valid")
else:
    print("Invalid url")

Output:

Url is valid

And for invalid URL:

import validators
valid=validators.url('gist.github.com/dperini/729294')
print(valid)
if valid==True:
    print("Url is valid")
else:
    print("Invalid url")

Output:

ValidationFailure(func=url, args={'value': 'gist.github.com/dperini/729294', 'public': False})
Invalid url

The validators module recognizes the pattern https://, ftp://  etc. for validating the URL and .com, .in, .something at the end of the URL.

To understand better about the pattern matching for validating the URL press Ctrl and click on the function name url written in code as follows:

valid=validators.url('https://codespeedy.com/')

A new page with name url.py  will open, and there you can see the pattern for validating URL.

That’s enough for this post. If you have any doubts relating to this post please comment below. For a tutorial on any topic of Python let us know in the comment section of this post.
If you found anything wrong in this post feel free to tell us.

Thank You.

 

Leave a Reply