urljoin Resolves Relative Links

Resolve relative links against a base URL with urllib.parse.urljoin, including query-only, fragment, and scheme-relative references.

PythonData Fetching

Code

pythonsnippet
30 lines
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

FAQ

Which packages must be installed first?
Yes. The imports resolve to `urllib`, which the package manager must provide.