urllib.parse — URL parsing and quoting

Python urllib.parse URL splitting and quoting, including why parsing is not validation, and the difference between quote and urlencode.

urllib.parse is a standard-library module for splitting and composing URL strings. It is not a third-party HTTP client, and calling it does not open a network connection. Import it with `from urllib.parse import urlparse, quote, urlencode`.

urlparse splits a string into components. It does not validate that the string is a legal or safe URL. quote and quote_plus encode a single string; urlencode builds a query string from a mapping or a sequence of pairs. urlencode uses quote_plus by default.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

urlparse is not validation

urlparse(urlstring, scheme='', allow_fragments=True) returns a ParseResult named 6-tuple: scheme, netloc, path, params, query, and fragment. Unusual or unsafe strings still parse. "not a url" becomes a result whose path is the original text. "javascript:alert(1)" is parsed with scheme "javascript".

If you need to accept only http and https URLs with a host, check those fields after parsing. The parse step itself will not reject the string.

urllib.parse.urlparse

urllib.parse.urlparse(urlstring, scheme='', allow_fragments=True)

Split a URL string into components. A successful parse is not a promise that the URL is valid, complete, or safe to request.

ParameterDescription
urlstringThe text to split. There is no request and no DNS lookup.
schemeA default scheme used when the string does not include one.
allow_fragmentsIf False, a # fragment is kept as part of the path, parameters, or query instead of a separate field.

Returns: A ParseResult named tuple. Access fields by name, such as result.scheme and result.netloc, or convert it with tuple().

  • This function never raises an error merely because the string does not look like a typical URL.
  • The examples stay off the network. Parsing a URL is not the same as fetching it.
python
from urllib.parse import urlparse

print(urlparse("https://example.com:8443/path?q=1#frag"))
print(urlparse("not a url"))
print(urlparse("javascript:alert(1)"))

Expected output

ParseResult(scheme='https', netloc='example.com:8443', path='/path', params='', query='q=1', fragment='frag')
ParseResult(scheme='', netloc='', path='not a url', params='', query='', fragment='')
ParseResult(scheme='javascript', netloc='', path='alert(1)', params='', query='', fragment='')

Official documentation →

quote, quote_plus, and urlencode

quote(string, safe='/') percent-encodes bytes that are not unreserved, and leaves characters in safe unchanged. The default safe='/' keeps slashes, which is appropriate for a path. quote_plus is intended for form values: it uses + for spaces and does not default safe to '/'.

urlencode(query, doseq=False, ..., quote_via=quote_plus) builds a query string. If a value is a list and doseq is False, the list is converted with str() and then quoted, which is almost never what you want. Pass doseq=True to emit one field per sequence item.

urllib.parse.quote, quote_plus, urlencode

urllib.parse.quote(string, safe='/', encoding=None, errors=None)
urllib.parse.quote_plus(string, safe='', encoding=None, errors=None)
urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None, quote_via=quote_plus)

Encode a string or a mapping for use in a URL. quote and quote_plus handle a single value; urlencode builds a query string and uses quote_plus unless you pass quote_via.

ParameterDescription
stringThe text to encode. Spaces become %20 with quote, and + with quote_plus.
safeCharacters that should not be quoted. quote defaults this to '/' ; quote_plus defaults it to an empty string.
queryA mapping or a sequence of two-item tuples.
doseqIf True, a sequence value becomes repeated keys. If False, the value is stringified as a whole.

Returns: A str containing the encoded result.

  • quote("a b/c") is a%20b/c. quote(..., safe="") is a%20b%2Fc. quote_plus("a b/c") is a+b%2Fc.
  • urlencode({"q": "a b", "tags": ["x", "y"]}) quotes the list's Python repr. With doseq=True it becomes q=a+b&tags=x&tags=y.
python
from urllib.parse import quote, quote_plus, urlencode

print(quote("a b/c"))
print(quote("a b/c", safe=""))
print(quote_plus("a b/c"))
print(urlencode({"q": "a b", "tags": ["x", "y"]}))
print(urlencode({"q": "a b", "tags": ["x", "y"]}, doseq=True))

Expected output

a%20b/c
a%20b%2Fc
a+b%2Fc
q=a+b&tags=%5B%27x%27%2C+%27y%27%5D
q=a+b&tags=x&tags=y

Official documentation →