How to validate a url in Python? (Malformed or not)


I have url from the user and I have to reply with the fetched HTML.

How can I check for the URL to be malformed or not?

For example :

url = 'google' # Malformed
url = '' # Malformed
url = '' # Valid
url = 'http://google' # Malformed
Asked By: Yugal Jindle



django url validation regex (source):

import re
regex = re.compile(
        r'^(?:http|ftp)s?://' # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?.)+(?:[A-Z]{2,6}.?|[A-Z0-9-]{2,}.?)|' #domain...
        r'localhost|' #localhost...
        r'd{1,3}.d{1,3}.d{1,3}.d{1,3})' # ...or ip
        r'(?::d+)?' # optional port
        r'(?:/?|[/?]S+)$', re.IGNORECASE)

print(re.match(regex, "") is not None) # True
print(re.match(regex, "") is not None)            # False
Answered By: cetver

Actually, I think this is the best way.

from django.core.validators import URLValidator
from django.core.exceptions import ValidationError

val = URLValidator(verify_exists=False)
except ValidationError, e:
    print e

If you set verify_exists to True, it will actually verify that the URL exists, otherwise it will just check if it’s formed correctly.

edit: ah yeah, this question is a duplicate of this: How can I check if a URL exists with Django’s validators?

Answered By: Drekembe

note – lepl is no longer supported, sorry (you’re welcome to use it, and i think the code below works, but it’s not going to get updates).

rfc 3696 defines how to do this (for http urls and email). i implemented its recommendations in python using lepl (a parser library). see

to use:

> easy_install lepl
> python
>>> from lepl.apps.rfc3696 import HttpUrl
>>> validator = HttpUrl()
>>> validator('google')
>>> validator('http://google')
>>> validator('')
Answered By: andrew cooke

Use the validators package:

>>> import validators
>>> validators.url("")
>>> validators.url("http://google")
ValidationFailure(func=url, args={'value': 'http://google', 'require_tld': True})
>>> if not validators.url("http://google"):
...     print "not valid"
not valid

Install it from PyPI with pip (pip install validators).

Answered By: Jabba

I landed on this page trying to figure out a sane way to validate strings as “valid” urls. I share here my solution using python3. No extra libraries required.

See if you are using python2.

See if you are using python3 as I am.

import urllib
from pprint import pprint

invalid_url = 'dkakasdkjdjakdjadjfalskdjfalk'
valid_url = ''
tokens = [urllib.parse.urlparse(url) for url in (invalid_url, valid_url)]

for token in tokens:

min_attributes = ('scheme', 'netloc')  # add attrs to your liking
for token in tokens:
    if not all([getattr(token, attr) for attr in min_attributes]):
        error = "'{url}' string has no scheme or netloc.".format(url=token.geturl())
        print("'{url}' is probably a valid url.".format(url=token.geturl()))

ParseResult(scheme=”, netloc=”, path=’dkakasdkjdjakdjadjfalskdjfalk’, params=”, query=”, fragment=”)

ParseResult(scheme=’https’, netloc=’’, path=”, params=”, query=”, fragment=”)

‘dkakasdkjdjakdjadjfalskdjfalk’ string has no scheme or netloc.‘ is probably a valid url.

Here is a more concise function:

from urllib.parse import urlparse

min_attributes = ('scheme', 'netloc')

def is_valid(url, qualifying=min_attributes):
    tokens = urlparse(url)
    return all([getattr(tokens, qualifying_attr)
                for qualifying_attr in qualifying])
Answered By: dmmfll

A True or False version, based on @DMfll answer:

    # python2
    from urlparse import urlparse
    # python3
    from urllib.parse import urlparse

a = ''
b = '/data/Python.html'
c = 532
d = u'dkakasdkjdjakdjadjfalskdjfalk'
e = ''

def uri_validator(x):
        result = urlparse(x)
        return all([result.scheme, result.netloc])
        return False



Answered By: alemol


As pointed out by @Kwame , the below code does validate the url even if the .com or .co etc are not present.

also pointed out by @Blaise, URLs like is a valid URL
and you need to do a DNS check for checking if it resolves or not, separately.

This is simple and works:

So min_attr contains the basic set of strings that needs to be present to define the validity of a URL,
i.e http:// part and part.

urlparse.scheme stores http:// and

urlparse.netloc store the domain name

from urlparse import urlparse
def url_check(url):

    min_attr = ('scheme' , 'netloc')
        result = urlparse(url)
        if all([result.scheme, result.netloc]):
            return True
            return False
        return False

all() returns true if all the variables inside it return true.
So if result.scheme and result.netloc is present i.e. has some value then the URL is valid and hence returns True.

Answered By: Padam Sethia

Nowadays, I use the following, based on the Padam’s answer:

$ python --version
Python 3.6.5

And this is how it looks:

from urllib.parse import urlparse

def is_url(url):
    result = urlparse(url)
    return all([result.scheme, result.netloc])
  except ValueError:
    return False

Just use is_url("").

Hope it helps!

Validate URL with urllib and Django-like regex

The Django URL validation regex was actually pretty good but I needed to tweak it a little bit for my use case. Feel free to adapt it to yours!

Python 3.7

import re
import urllib

# Check for reference
DOMAIN_FORMAT = re.compile(
    r"(?:^(w{1,255}):(.{1,255})@|^)" # http basic authentication [optional]
    r"(?:(?:(?=S{0,253}(?:$|:))" # check full domain length to be less than or equal to 253 (starting after http basic auth, stopping before port)
    r"((?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?.)+" # check for at least one subdomain (maximum length per subdomain: 63 characters), dashes in between allowed
    r"(?:[a-z0-9]{1,63})))" # check for top level domain, no dashes allowed
    r"|localhost)" # accept also "localhost" only
    r"(:d{1,5})?", # port [optional]
SCHEME_FORMAT = re.compile(
    r"^(http|hxxp|ftp|fxp)s?$", # scheme: http(s) or ftp(s)

def validate_url(url: str):
    url = url.strip()

    if not url:
        raise Exception("No URL specified")

    if len(url) > 2048:
        raise Exception("URL exceeds its maximum length of 2048 characters (given length={})".format(len(url)))

    result = urllib.parse.urlparse(url)
    scheme = result.scheme
    domain = result.netloc

    if not scheme:
        raise Exception("No URL scheme specified")

    if not re.fullmatch(SCHEME_FORMAT, scheme):
        raise Exception("URL scheme must either be http(s) or ftp(s) (given scheme={})".format(scheme))

    if not domain:
        raise Exception("No URL domain specified")

    if not re.fullmatch(DOMAIN_FORMAT, domain):
        raise Exception("URL domain malformed (domain={})".format(domain))

    return url


  • The code only validates the scheme and netloc part of a given URL. (To do this properly, I split the URL with urllib.parse.urlparse() in the two according parts which are then matched with the corresponding regex terms.)
  • The netloc part stops before the first occurrence of a slash /, so port numbers are still part of the netloc, e.g.:
    ^^^^^   ^^^^^^^^^^^^^^^^^
      |             |      
      |             +-- netloc (aka "domain" in my code)
      +-- scheme
  • IPv4 addresses are also validated

IPv6 Support

If you want the URL validator to also work with IPv6 addresses, do the following:

  • Add is_valid_ipv6(ip) from Markus Jarderot’s answer, which has a really good IPv6 validator regex
  • Add and not is_valid_ipv6(domain) to the last if


Here are some examples of the regex for the netloc (aka domain) part in action:

Answered By: winklerrr

All of the above solutions recognize a string like “,” as valid. This solution always works as it should

import re

# URL-link validation
ip_middle_octet = u"(?:.(?:1?d{1,2}|2[0-4]d|25[0-5]))"
ip_last_octet = u"(?:.(?:[1-9]d?|1dd|2[0-4]d|25[0-4]))"

URL_PATTERN = re.compile(
                        # protocol identifier
                        # user:pass authentication
                        u"(?:S+(?::S*)[email protected])?"
                        # IP address exclusion
                        # private & local networks
                        u"(?:(?:10|127)" + ip_middle_octet + u"{2}" + ip_last_octet + u")|"
                        u"(?:(?:169.254|192.168)" + ip_middle_octet + ip_last_octet + u")|"
                        u"(?:172.(?:1[6-9]|2d|3[0-1])" + ip_middle_octet + ip_last_octet + u"))"
                        # IP address dotted notation octets
                        # excludes loopback network
                        # excludes reserved space >=
                        # excludes network & broadcast addresses
                        # (first & last IP address of each class)
                        u"" + ip_middle_octet + u"{2}"
                        u"" + ip_last_octet + u")"
                        # host name
                        # domain name
                        # TLD identifier
                        # port number
                        # resource path
                        # query string
                        re.UNICODE | re.IGNORECASE
def url_validate(url):   
    """ URL string validation
    return re.compile(URL_PATTERN).match(url)

Not directly relevant, but often it’s required to identify whether some token CAN be a url or not, not necessarily 100% correctly formed (ie, https part omitted and so on). I’ve read this post and did not find the solution, so I am posting my own here for the sake of completeness.

def get_domain_suffixes():
    import requests
    for line in res.text.split('n'):
        if not line.startswith('//'):
            if cand:
    return tuple(sorted(lst))


def reminds_url(txt:str):
    >>> reminds_url('')
    return ltext.startswith(('http','www','ftp')) or ltext.endswith(domain_suffixes)
Answered By: Anatoly Alekseev

Here’s a regex solution since top voted regex doesn’t work for weird cases like top-level domain. Some test cases down below.

regex = re.compile(
    r"(w+://)?"                # protocol                      (optional)
    r"(w+.)?"                 # host                          (optional)
    r"((w+).(w+))"           # domain
    r"(.w+)*"                 # top-level domain              (optional, can have > 1)
    r"([w-._~/]*)*(?<!.)"  # path, params, anchors, etc.   (optional)
cases = [
    # top level
for c in cases:
    print(c, regex.match(c).span()[1] - regex.match(c).span()[0] == len(c))
Answered By: Dominic Tarro

Function based on Dominic Tarro answer:

import re
def is_url(x):
    return bool(re.match(
        r"(https?|ftp)://" # protocol
        r"(w+(-w+)*.)?" # host (optional)
        r"((w+(-w+)*).(w+))" # domain
        r"(.w+)*" # top-level domain (optional, can have > 1)
        r"([w-._~/]*)*(?<!.)" # path, params, anchors, etc. (optional)
    , x))
Answered By: pmiguelpinto

Pydantic could be used to do that. I’m not very used to it so I can’t say about it’s limitations. It is an option thou and no one suggested it.

I have seen that many people questioned about ftp and files URL in previous answers so I recommend to get known to the documentation as Pydantic have many types for validation as FileUrl, AnyUrl and even database url types.

A simplistic usage example:

from requests import get, HTTPError, ConnectionError
from pydantic import BaseModel, AnyHttpUrl, ValidationError
class MyConfModel(BaseModel):
    URI: AnyHttpUrl

    myAddress = MyConfModel(URI = "")
    req = get(myAddress.URI, verify=False)

    print('Invalid destination')

Pydantic also raises exceptions (pydantic.ValidationError) that can be used to handle errors.

I have teste it with these patterns:

Answered By: dxtr_brz
from urllib.parse import urlparse

def is_valid_url(url):
        result = urlparse(url)
        return all([result.scheme, result.netloc])
    except ValueError:
        return False

url = ''
if is_valid_url(url):
    print('Valid URL')
    print('Malformed URL')
Answered By: Hà Nguyễn