Parsing URLs

suggest change

The urllib.parse module from the standard library splits URLs into their components, builds them back, encodes and decodes query strings, percent-encodes text and resolves relative links. You don't need a third-party package for any of it.

The most useful functions are:

Function What it does
urlsplit() splits a URL into scheme, netloc, path, query and fragment
urlunsplit() builds a URL from those 5 parts
parse_qs(), parse_qsl() decode a query string into a dict or a list of pairs
urlencode() encodes a dict or list of pairs into a query string
quote(), unquote() percent-encode and decode text
urljoin() resolves a relative URL against a base URL
urldefrag() removes the #fragment

This article covers parsing and building URLs. To download a URL see HTTP GET and HTTP POST.

All examples were run with Python 3.13.

Splitting a URL with urlsplit

urlsplit() returns a SplitResult, a named tuple with 5 fields plus a few computed attributes:

from urllib.parse import urlsplit

url = "https://alice:secret@Example.COM:8443/docs/index.html?lang=en&page=2#install"
parts = urlsplit(url)

print(parts)
print("scheme:  ", parts.scheme)
print("netloc:  ", parts.netloc)
print("path:    ", parts.path)
print("query:   ", parts.query)
print("fragment:", parts.fragment)
print("username:", parts.username)
print("password:", parts.password)
print("hostname:", parts.hostname)
print("port:    ", parts.port)
SplitResult(scheme='https', netloc='alice:secret@Example.COM:8443', path='/docs/index.html', query='lang=en&page=2', fragment='install')
scheme:   https
netloc:   alice:secret@Example.COM:8443
path:     /docs/index.html
query:    lang=en&page=2
fragment: install
username: alice
password: secret
hostname: example.com
port:     8443

netloc (network location) is the raw user:password@host:port part. Use hostname and port instead of splitting netloc yourself: hostname is lowercased and port is converted to an int.

port is None when the URL doesn't have one; it is not filled in with the default port for the scheme. An invalid port raises ValueError, but only when you access the port attribute. urlsplit() itself doesn't validate it:

from urllib.parse import urlsplit

print(urlsplit("https://example.com/").port)
print(urlsplit("https://example.com:99999/").netloc)
try:
    urlsplit("https://example.com:99999/").port
except ValueError as e:
    print("ValueError:", e)
try:
    urlsplit("https://example.com:http/").port
except ValueError as e:
    print("ValueError:", e)

ipv6 = urlsplit("http://[2001:db8::1]:8080/status")
print(ipv6.netloc, ipv6.hostname, ipv6.port)
None
example.com:99999
ValueError: Port out of range 0-65535
ValueError: Port could not be cast to integer value as 'http'
[2001:db8::1]:8080 2001:db8::1 8080

For IPv6 addresses hostname returns the address without the square brackets.

urlsplit vs. urlparse

urlparse() is the older function. It does the same thing, but also splits off ;params from the last path segment, a feature of an old URL standard that nobody uses anymore:

from urllib.parse import urlsplit, urlparse

url = "http://example.com/path;type=a?x=1"
print(urlsplit(url))
print(urlparse(url))

# the tuple interface still works
scheme, netloc, path, query, fragment = urlsplit("ftp://files.example.org/pub/readme.txt")
print(scheme, netloc, path)
SplitResult(scheme='http', netloc='example.com', path='/path;type=a', query='x=1', fragment='')
ParseResult(scheme='http', netloc='example.com', path='/path', params='type=a', query='x=1', fragment='')
ftp files.example.org /pub/readme.txt

Use urlsplit() in new code. With urlparse() a ; in a path silently ends up in params instead of path.

URLs without a scheme

urlsplit() follows the URL syntax strictly. Something that looks like a host name to a human is just a path if there is no // in front of it:

from urllib.parse import urlsplit

urls = [
    "example.com/about",
    "//example.com/about",
    "localhost:8000/api",
    "mailto:bob@example.com",
    "/search?q=python",
]
for url in urls:
    p = urlsplit(url)
    print(f"{url:24} scheme={p.scheme!r:12} netloc={p.netloc!r:15} path={p.path!r}")
example.com/about        scheme=''           netloc=''              path='example.com/about'
//example.com/about      scheme=''           netloc='example.com'   path='/about'
localhost:8000/api       scheme='localhost'  netloc=''              path='8000/api'
mailto:bob@example.com   scheme='mailto'     netloc=''              path='bob@example.com'
/search?q=python         scheme=''           netloc=''              path='/search'

Note localhost:8000/api: localhost is a valid scheme name, so it's parsed as scheme localhost.

If you accept URLs typed by users, add the missing // before parsing and pass a default scheme:

from urllib.parse import urlsplit

def parse_user_url(text, default_scheme="https"):
    text = text.strip()
    if "://" not in text and not text.startswith("//"):
        text = "//" + text
    parts = urlsplit(text, scheme=default_scheme)
    if not parts.hostname:
        raise ValueError(f"no host in {text!r}")
    return parts

print(parse_user_url("example.com/about"))
print(parse_user_url("localhost:8000/api"))
print(parse_user_url("http://example.com"))
SplitResult(scheme='https', netloc='example.com', path='/about', query='', fragment='')
SplitResult(scheme='https', netloc='localhost:8000', path='/api', query='', fragment='')
SplitResult(scheme='http', netloc='example.com', path='', query='', fragment='')

The scheme argument is only used when the URL has no scheme of its own.

Building URLs with urlunsplit and _replace

urlunsplit() takes a 5-tuple and returns a URL string. To change one part of an existing URL, use the named tuple's _replace() method and then geturl():

from urllib.parse import urlsplit, urlunsplit

parts = urlsplit("http://example.com/old/path?a=1#top")

new = parts._replace(scheme="https", path="/new/path", fragment="")
print(new.geturl())

print(urlunsplit(("https", "api.example.com:8443", "/v1/users", "limit=10", "")))
print(urlunsplit(("", "", "/just/a/path", "", "")))
https://example.com/new/path?a=1
https://api.example.com:8443/v1/users?limit=10
/just/a/path

urlunsplit() doesn't encode anything. Each part must already be properly percent-encoded (see below).

Parsing query strings

parse_qs() returns a dict mapping each name to a list of values, because a name can appear more than once. parse_qsl() returns a list of (name, value) pairs in the original order:

from urllib.parse import parse_qs, parse_qsl

query = "tag=python&tag=web&page=2&empty=&flag"

print(parse_qs(query))
print(parse_qsl(query))
print(parse_qs(query, keep_blank_values=True))
print(parse_qsl(query, keep_blank_values=True))

print(parse_qs("q=caf%C3%A9+au+lait&sym=%26%3D"))
{'tag': ['python', 'web'], 'page': ['2']}
[('tag', 'python'), ('tag', 'web'), ('page', '2')]
{'tag': ['python', 'web'], 'page': ['2'], 'empty': [''], 'flag': ['']}
[('tag', 'python'), ('tag', 'web'), ('page', '2'), ('empty', ''), ('flag', '')]
{'q': ['café au lait'], 'sym': ['&=']}

By default, parameters with empty values are dropped. Pass keep_blank_values=True if ?flag or ?name= means something in your application.

Values are decoded for you: + becomes a space and %XX sequences are decoded as UTF-8.

Since every value is a list, reading a single parameter needs a default and an index:

from urllib.parse import parse_qs, urlsplit

url = "https://shop.example.com/search?q=red+shoes&size=42&size=43&sort=price"
params = parse_qs(urlsplit(url).query)

query = params.get("q", [""])[0]
sizes = [int(s) for s in params.get("size", [])]
page = int(params.get("page", ["1"])[0])

print(query, sizes, page)
red shoes [42, 43] 1

When parsing query strings from untrusted clients, limit the number of fields with max_num_fields. strict_parsing=True turns malformed fields into errors instead of ignoring them. Only & separates fields (since Python 3.9.2); pass separator if you need ;:

from urllib.parse import parse_qs

try:
    parse_qs("a=1&b=2&c=3&d=4", max_num_fields=3)
except ValueError as e:
    print("ValueError:", e)

try:
    parse_qs("a=1&bad", strict_parsing=True)
except ValueError as e:
    print("ValueError:", e)

print(parse_qs("a=1;b=2"))
print(parse_qs("a=1;b=2", separator=";"))
ValueError: Max number of fields exceeded
ValueError: bad query field: 'bad'
{'a': ['1;b=2']}
{'a': ['1'], 'b': ['2']}

Building query strings with urlencode

urlencode() is the inverse of parse_qs(). It accepts a dict or a list of pairs, converts values with str() and encodes them:

from urllib.parse import urlencode, quote

params = {"q": "café & bar", "page": 2, "debug": True}
print(urlencode(params))

# a list value becomes a single, encoded string unless doseq=True
print(urlencode({"tag": ["python", "web"]}))
print(urlencode({"tag": ["python", "web"]}, doseq=True))

# list of pairs keeps order and allows repeated keys
print(urlencode([("sort", "name"), ("sort", "date")]))

# spaces as %20 instead of +
print(urlencode({"q": "red shoes"}, quote_via=quote))
q=caf%C3%A9+%26+bar&page=2&debug=True
tag=%5B%27python%27%2C+%27web%27%5D
tag=python&tag=web
sort=name&sort=date
q=red%20shoes

Two things to watch out for:

Never build a query string with f-strings or +. A value containing &, =, # or a space would break the URL or inject extra parameters.

Combining urlsplit(), parse_qsl() and urlencode() gives a helper that adds, changes or removes query parameters of an existing URL:

from urllib.parse import urlsplit, urlunsplit, parse_qsl, urlencode

def set_query_params(url, **updates):
    parts = urlsplit(url)
    params = dict(parse_qsl(parts.query, keep_blank_values=True))
    for key, value in updates.items():
        if value is None:
            params.pop(key, None)
        else:
            params[key] = value
    return urlunsplit(parts._replace(query=urlencode(params)))

url = "https://example.com/list?page=1&sort=name&utm_source=mail"
print(set_query_params(url, page=2))
print(set_query_params(url, utm_source=None, filter="active items"))
https://example.com/list?page=2&sort=name&utm_source=mail
https://example.com/list?page=1&sort=name&filter=active+items

Converting to a dict keeps only the last value of repeated parameters. Work on the list of pairs if you need to keep all of them.

Percent-encoding with quote and unquote

Characters that aren't allowed in a URL are written as %XX, where XX is the hex value of a byte of the UTF-8 encoding.

from urllib.parse import quote, quote_plus, unquote, unquote_plus

print(quote("/files/my report (final).pdf"))
print(quote("a/b c", safe=""))
print(quote_plus("a/b c&d=e"))
print(quote("zażółć"))
print(quote("été", encoding="latin-1"))

print(unquote("/files/my%20report%20%28final%29.pdf"))
print(unquote("a+b%20c"))
print(unquote_plus("a+b%20c"))
print(unquote("za%C5%BC%C3%B3%C5%82%C4%87"))
print(unquote("%E9t%E9", encoding="latin-1"))
print(unquote("%E9t%E9"))
/files/my%20report%20%28final%29.pdf
a%2Fb%20c
a%2Fb+c%26d%3De
za%C5%BC%C3%B3%C5%82%C4%87
%E9t%E9
/files/my report (final).pdf
a+b c
a b c
zażółć
été
�t�

The last line shows that invalid UTF-8 doesn't raise an error: unquote() uses errors="replace" and puts U+FFFD replacement characters in the result.

When you put a value into a single path segment, pass safe="" so that a / in the value is encoded too. Otherwise a user name like john/../admin changes which resource the URL points to:

from urllib.parse import quote, urlunsplit

user = "john/../admin"
print("bad: ", "https://api.example.com/users/" + user)
print("good:", "https://api.example.com/users/" + quote(user, safe=""))

segments = ["docs", "C# & .NET", "100%"]
path = "/" + "/".join(quote(s, safe="") for s in segments)
print(urlunsplit(("https", "example.com", path, "", "")))
bad:  https://api.example.com/users/john/../admin
good: https://api.example.com/users/john%2F..%2Fadmin
https://example.com/docs/C%23%20%26%20.NET/100%25

Encode each piece exactly once. Encoding an already encoded string turns %20 into %2520, and decoding twice can turn %2525 into %, which is a common source of security bugs.

Resolving relative URLs with urljoin

urljoin(base, ref) resolves a link the way a browser does, for example an href found on a page you downloaded:

from urllib.parse import urljoin

base = "https://example.com/docs/guide/intro.html"

for ref in ["setup.html", "../api/", "/about", "?page=2", "#install",
            "//cdn.example.net/app.js", "https://other.org/x"]:
    print(f"{ref:26} -> {urljoin(base, ref)}")
setup.html                 -> https://example.com/docs/guide/setup.html
../api/                    -> https://example.com/docs/api/
/about                     -> https://example.com/about
?page=2                    -> https://example.com/docs/guide/intro.html?page=2
#install                   -> https://example.com/docs/guide/intro.html#install
//cdn.example.net/app.js   -> https://cdn.example.net/app.js
https://other.org/x        -> https://other.org/x

Because it follows browser rules, urljoin() is a poor tool for gluing an API base URL and an endpoint. The last path segment of the base is replaced unless the base ends with /, and a reference starting with / throws away the whole base path:

from urllib.parse import urljoin

print(urljoin("https://api.example.com/v1", "users"))
print(urljoin("https://api.example.com/v1/", "users"))
print(urljoin("https://api.example.com/v1/", "/users"))
https://api.example.com/users
https://api.example.com/v1/users
https://api.example.com/users

Only the middle form keeps /v1. For API clients, store the base URL with a trailing / and use relative endpoint names, or just concatenate strings you control.

Removing the fragment with urldefrag

The #fragment is never sent to the server. urldefrag() strips it, which is handy for de-duplicating links in a crawler:

from urllib.parse import urldefrag

result = urldefrag("https://example.com/docs/page.html?x=1#section-2")
print(result)
print(result.url)
print(result.fragment)
DefragResult(url='https://example.com/docs/page.html?x=1', fragment='section-2')
https://example.com/docs/page.html?x=1
section-2

Validating URLs

urlsplit() is not a validator. It accepts almost any string and rarely raises. A few behaviours matter when the URL comes from an untrusted source:

from urllib.parse import urlsplit

# leading spaces are stripped, tabs and newlines are removed anywhere
print(urlsplit("  https://example.com/a\tb\nc"))

# userinfo: everything before the last @ is the user name
print(urlsplit("https://trusted.com@evil.com/").hostname)

# browsers treat \ like / in http(s) URLs, Python doesn't
print(urlsplit(r"https://evil.com\@trusted.com/").hostname)

# schemes are lowercased
print(urlsplit("JavaScript:alert(1)").scheme)
SplitResult(scheme='https', netloc='example.com', path='/abc', query='', fragment='')
evil.com
trusted.com
javascript

The third case is a parser differential: Python reports trusted.com, but a browser would go to evil.com. Checks like "does the host end with trusted.com" or "does the URL start with https://trusted.com" are easy to bypass.

A typical place where this matters is a login page that redirects to a ?next= URL. An open redirect lets attackers send users to a phishing site through your domain. Check the scheme and compare the exact host against an allow-list, and reject characters browsers treat specially:

from urllib.parse import urlsplit

ALLOWED_HOSTS = {"example.com", "www.example.com"}

def is_safe_redirect(target):
    if any(c in target for c in "\\\t\r\n") or target.startswith("//"):
        return False
    parts = urlsplit(target)
    if not parts.scheme and not parts.netloc:
        # relative URL like "/account" stays on our site
        return target.startswith("/")
    return parts.scheme in ("http", "https") and parts.hostname in ALLOWED_HOSTS

tests = [
    "/account/settings",
    "https://www.example.com/welcome",
    "https://evil.com/phish",
    "//evil.com/phish",
    "https://example.com@evil.com/",
    "https://example.com.evil.com/",
    r"https://evil.com\@example.com/",
    "javascript:alert(1)",
    "/\tevil.com",
]
for t in tests:
    print(f"{t!r:36} {is_safe_redirect(t)}")
'/account/settings'                  True
'https://www.example.com/welcome'    True
'https://evil.com/phish'             False
'//evil.com/phish'                   False
'https://example.com@evil.com/'      False
'https://example.com.evil.com/'      False
'https://evil.com\\@example.com/'    False
'javascript:alert(1)'                False
'/\tevil.com'                        False

//evil.com is a protocol-relative URL, so a browser treats it as an absolute URL to another host. Web frameworks have tested helpers for this (Django's url_has_allowed_host_and_scheme()); prefer them when available. See Application security for more.

Normalizing URLs for comparison

Different strings can refer to the same resource: HTTPS://Example.COM:443/a%7Eb and https://example.com/a~b are equivalent. To compare or de-duplicate URLs, normalize them first. This function lowercases the scheme and host, drops default ports and the fragment, converts international domain names to their ASCII (Punycode) form and re-encodes the path consistently:

from urllib.parse import urlsplit, urlunsplit, quote, unquote

def normalize_url(url):
    parts = urlsplit(url)
    scheme = parts.scheme.lower()
    host = parts.hostname or ""
    if ":" in host:  # IPv6 literal needs brackets back
        host = f"[{host}]"
    else:
        host = host.encode("idna").decode("ascii")
    port = parts.port
    default_port = {"http": 80, "https": 443}.get(scheme)
    netloc = host if port in (None, default_port) else f"{host}:{port}"
    path = quote(unquote(parts.path), safe="/") or "/"
    return urlunsplit((scheme, netloc, path, parts.query, ""))

print(normalize_url("HTTPS://Example.COM:443/a%7Eb/c d#top"))
print(normalize_url("http://example.com"))
print(normalize_url("http://example.com:8080/x?b=2&a=1"))
print(normalize_url("https://bücher.example/katalog"))
print(normalize_url("http://[2001:DB8::1]:80/"))
https://example.com/a~b/c%20d
http://example.com/
http://example.com:8080/x?b=2&a=1
https://xn--bcher-kva.example/katalog
http://[2001:db8::1]/

The user name and password are dropped on purpose. The query is left alone, because the order of parameters can be significant to the server. Decoding and re-encoding the path also turns an encoded %2F into a real /, so don't use this on URLs where that distinction matters.

The built-in idna codec implements the older IDNA 2003 standard. For full IDNA 2008 support install the idna package from PyPI.

Paths and file names from URLs

To get the file name or extension from a URL, decode the path and hand it to pathlib.PurePosixPath. URL paths always use /, so use the POSIX flavour even on Windows. For file: URLs, pathlib converts in both directions:

from pathlib import Path, PurePosixPath
from urllib.parse import urlsplit, unquote

url = "https://example.com/downloads/reports/Q3%20summary.tar.gz?v=2"
path = PurePosixPath(unquote(urlsplit(url).path))
print(path.name, path.suffixes, path.parent)

# file: URLs (output from Windows)
uri = Path("C:/Users/me/My Files/a.txt").as_uri()
print(uri)
print(Path.from_uri(uri))
Q3 summary.tar.gz ['.tar', '.gz'] /downloads/reports
file:///C:/Users/me/My%20Files/a.txt
C:\Users\me\My Files\a.txt

Path.from_uri() was added in Python 3.13. On Linux and macOS, Path("/home/me/My Files/a.txt").as_uri() gives file:///home/me/My%20Files/a.txt.

Never use a name taken from a URL as a local file name without checking it. A decoded path can contain .. segments.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents