Separate a fragment from a local documentation URL
A documentation link can identify both a local document and a section within it. In this example, urldefrag receives guides/install.html#environment-variables and returns a structured result with two values: the document URL guides/install.html and the fragment environment-variables. Assertions make the intended split explicit before the two values are printed.
A fragment is client-side reference information, not part of the document path. Removing it is useful when a program wants to group several section links under one documentation page while retaining the anchor for presentation or navigation. urldefrag avoids manually searching for #, and its result exposes named url and fragment attributes. Structured return results for this function are available from Python 3.2 onward.
This does not turn the relative URL into a filesystem path, resolve .. segments, confirm that the document exists, or check that the anchor is present in the document. It also does not fetch anything. If a program must resolve a relative reference against a base URL, it needs a separate, carefully scoped URL-resolution step.
See the official urllib.parse documentation. AI assistance disclosure: this article was drafted with AI assistance and should be checked against the project's link conventions.
from urllib.parse import urldefrag
reference = "guides/install.html#environment-variables"
result = urldefrag(reference)
assert result.url == "guides/install.html"
assert result.fragment == "environment-variables"
print(f"document={result.url}")
print(f"fragment={result.fragment}")
document=guides/install.html
fragment=environment-variables