Split URLs and Validate Their Components
Core idea
Use urlsplit to separate a URL into scheme, network location, path, query and fragment. hostname exposes the host and port exposes the numeric port. Parsing is not validation: define which schemes and hosts your application accepts before using a URL. Use urlencode for query values rather than concatenating raw strings.
from urllib.parse import urlsplitu = urlsplit('https://reports.example:8443/daily?zone=north#top')print(u.scheme, u.hostname, u.port)print(u.path, u.query, u.fragment)The fragment is separate from the query; neither is part of the hostname.
Apply a narrow local policy
from urllib.parse import urlsplit, urlencodedef allowed(text): try: u = urlsplit(text) return (u.scheme == 'https' and u.hostname == 'reports.example' and u.port in (None, 443) and u.username is None and u.password is None) except ValueError: return Falseprint(allowed('https://reports.example/daily'))print(allowed('https://reports.example:99999/daily'))print(urlencode({'zone': 'north & west'}))The example policy accepts a specific host and port only; the query encoder protects delimiters in values. It is not a full network security policy.
Common mistake
Never treat successful parsing as permission to fetch. Redirects, DNS resolution, address ranges and application authorization require separate controls. urljoin can replace the host if given an absolute second URL.
Practice
Extend the local policy to reject fragments; test a relative path, a wrong host and a valid URL without sending requests.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
URL parsing
Check your understanding of url parsing.
What is printed?
from urllib.parse import urlsplitprint(urlsplit('https://example.test/a?x=1').path)What is printed?
from urllib.parse import urlencodeprint(urlencode({'q':'a+b'}))What does a successful urlsplit prove?
Which property gives a numeric explicit port?