Python: how to validate a URL

In this article we will see how to validate a URL with Python.

We can install the validators module for the purpose we want to achieve.

pip install validators

This module has a series of helper methods that implement the various types of validation required by returning a boolean value indicating the result of the validation performed. To validate a URL we can use the following approach:

import validators

def is_url(url):
    return validators.url(url)
    
def main():
    valid_url = 'https://gabrieleromanato.com'
    invalid_url = 'https://'
    
    print(is_url(valid_url))
    print(is_url(invalid_url))
    
if __name__ == '__main__':
    main()        

We will get:

True
False
Back to top