urljoin Resolves Relative Links
Resolve relative links against a base URL with urllib.parse.urljoin, including query-only, fragment, and scheme-relative references.
Code
from urllib.parse import urljoin, urlparse
BASE = 'https://devexamples.com/docs/guide/intro.html?lang=en'
def resolve(link: str) -> str:
joined = urljoin(BASE, link)
return urlparse(joined).geturl()
def main() -> None:
links = [
'../api/',
'/examples/python/',
'?page=2',
'#section',
'//cdn.example.com/app.js',
]
for link in links:
print(link, '->', resolve(link))
parsed = urlparse(resolve('../api/'))
print('host:', parsed.hostname)
print('path:', parsed.path)
print('query:', parsed.query or '(none)')
if __name__ == '__main__':
main()How the snippet works
The code’s whole job belongs to the functions resolve and main.
The one repetition in this snippet is the loop for link in links. The snippet’s external surface is urljoin, urlparse, all of it via urllib.
Points of care
- External dependency:
urllib— install it before running the snippet.
Applying it
Entry signature: def resolve(link: str) -> str
Running the file prints labeled results such as host:, path:, query: — each operation’s effect is visible in the output.
The demo flow inside main is resolve — run the file to see it end to end.
Statements that matter
def main() -> None:
links = [
'../api/',
'/examples/python/',
'?page=2',
'#section',
'//cdn.example.com/app.js',
]
for link in links:
print(link, '->', resolve(link))
parsed = urlparse(resolve('../api/'))
print('host:', parsed.hostname)
def resolve(link: str) -> str:
joined = urljoin(BASE, link)
return urlparse(joined).geturl()
Interactive Tools for This Topic
Base64url CodecEncode and decode Base64url, the URL- and filename-safe variant that swaps + and / for - and _ and omits padding.Markdown Link ExtractorExtract inline and reference-style links from Markdown with titles and definitions resolved into a plain list.Nano ID GeneratorGenerate URL-safe Nano ID strings with a configurable length and alphabet using the Web Crypto API.Query String ParserParse a query string or URL into decoded key-value rows, preserving repeated keys and empty values for debugging and API work.
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `urllib`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.