How to Check If a String Is a Valid URL in Python
Learn how to validate URLs in Python with the validators and django url validator
How to check if a URL is valid in python? You'll be surprise how easy it is to check that.
In this article you'll learn how to determine if a string is a valid web address or not.
The good new is, you don't need to write your own URL validator. We'll see how we can leverage a third-party URL validator to do the job for us.
validators package is a tool that comes with a wide range of validation utilities. You can validate all sorts of inputs such as emails, IP addresses, bitcoin addresses and, of course, URLs.
The URL validation function is available in the root of the module and will return True if the string is a valid URL, otherwise it returns an instance of
ValidationFailure, which is a bit weird but not a deal breaker.
import validators validators.url("http://localhost:8000") True
The function from previous section can be re-written as follows:
import validators ... def is_string_an_url(url_string: str) -> bool: result = validators.url(url_string) if isinstance(result, ValidationFailure): return False return result ... is_string_an_url("http://localhost:8000") True is_string_an_url("http://.www.foo.bar/") False
django is a great web framework that has many features. It bundles several utilities that makes web development easier. One such utility is the
validators module, which contains, amongst other things, an URL validator.
You can validate if a string is, or not, an URL by creating an instance of
URLValidator and calling it.
from django.core.validators import URLValidator from django.core.exceptions import ValidationError ... def is_string_an_url(url_string: str) -> bool: validate_url = URLValidator(verify_exists=True) try: validate_url(url_string) except ValidationError, e: return False return True
This works well, but adding Django as a dependency just to use its validator is a bit too much. Unless, of course, your project already has Django as a part of it. If not, we have another alternative.
In this post we saw 2 different ways of validating a URL in Python. I hope you find it useful.
Other posts you may like:
- Design Patterns That Make Sense in Python: Simple Factory
- How to Pass Multiple Arguments to a map Function in Python
- 73 Examples to Help You Master Python's f-strings
- Everything You Need to Know About Python's Namedtuples
- The Best Way to Compare Two Dictionaries in Python
- 5 Hidden Python Features You Probably Never Heard Of
See you next time!