How to validate a URL with a regular expression in Python?

Sometimes, we want to validate a URL with a regular expression in Python.

In this article, we’ll look at how to validate a URL with a regular expression in Python.

How to validate a URL with a regular expression in Python?

To validate a URL with a regular expression in Python, w ecan use the PreparedRequest class from the requests library.

For instance, we write

from requests.models import PreparedRequest
import requests.exceptions


def check_url(url):
    prepared_request = PreparedRequest()
    try:
        prepared_request.prepare_url(url, None)
        return prepared_request.url
    except requests.exceptions.MissingSchema, e:
        raise SomeException

to create the check_url function.

In it, we create a PreparedRequest object.

Then we call prepare_url with the url parameter to try to parse the url string as a URL.

If it succeeds, we return prepared_request.url.

Otherwise, the requests.exceptions.MissingSchema will be raised and we catch that.

Conclusion

To validate a URL with a regular expression in Python, w ecan use the PreparedRequest class from the requests library.