How to Check If a String Is a Valid URL in Python
In this article you'll learn how to determine if a string is a valid URL or not.
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.
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
In this post we saw 2 different ways of validating a URL in Python. I hope you find it useful.
If you liked this post, consider sharing it with your friends or buying me a coffee:)
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
- 3 Ways to Test API Client Applications in Python
- 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!