all Python 3urllib.parsefunction
urllib.parse.urljoin()
URL parsing
Builds an absolute URL from a base address and a relative link — the way a browser does.
Syntax
urllib.parse.urljoin(base, url, allow_fragments=True)
A link with a leading '/' replaces the whole base path instead of being appended: urljoin('http://h/api/v1', '/users') gives http://h/users. Without a trailing '/' the last base segment is dropped: 'http://h/api' + 'users' → http://h/users. An absolute link ('//evil.com/x' or 'https://…') replaces the base entirely, so joining user input this way is unsafe.
Examples
from urllib.parse import urljoin
print(urljoin('http://h/api/v1/', '/users')) # → http://h/users
print(urljoin('http://h/api/v1/', 'users')) # → http://h/api/v1/users
print(urljoin('http://h/api/v1', 'users')) # → http://h/api/users
from urllib.parse import urljoin
print(urljoin('http://h/a/b', '//evil.com/x')) # → http://evil.com/x
print(urljoin('http://h/a/', '../x')) # → http://h/x
See also
Open in the full glossarydocs.python.orgReport an inaccuracy