Sub topic 5
Discovering and normalizing URLs
This chapter assumes you can read short Python snippets, know how HTTP requests and status codes work, and know how an <a href> link is structured. The previous chapter showed how a parser pulls href values out of HTML. Those values are raw strings, and this chapter covers what happens to them next.
Discovery is not fetching
A crawler learns about a URL long before it requests it. Discovery means adding a URL to the set of addresses the system knows exist. Fetching means requesting it over HTTP. Keeping the two apart lets a crawler record millions of candidate URLs cheaply and then decide, later and with other rules, which ones to fetch.
Common sources of discovered URLs:
- Links in pages that were already fetched. This is the main source.
- XML sitemaps that site owners publish (covered in the next chapter).
- Redirect targets, taken from the
Locationheader of a 301, 302, 307, or 308 response. - Canonical hints, such as
<link rel="canonical">tags, which name another URL for the same content. - URLs from earlier crawls, which are kept and revisited.
- Feeds, external submissions, and URL-like strings found in rendered JavaScript output.
Each discovered URL is stored with its source and the time it was found. A URL found on many pages is usually a stronger signal than one found only in a sitemap.
Why raw links need cleaning
A parser returns exactly what the author typed. That might be ../intro.html, //cdn.example.com/a.js, HTTPS://Example.com:443/a#top, or javascript:void(0). If the crawler stored these strings unchanged, it would have three problems:
- It could not fetch relative links, because they have no host.
- It would treat different spellings of one address as different pages, and fetch the same page repeatedly.
- It would try to fetch things that are not web pages at all, such as
mailto:links.
URL normalization converts every discovered string into one consistent absolute form, called the canonical form here only in the sense of "the crawler's internal key". Do not confuse it with canonical URLs for duplicate content, which a later chapter covers. Normalization is purely mechanical string work. It never fetches anything and never judges whether two pages have the same content.
Resolving relative links
A relative link is resolved against a base URL. Usually the base is the address of the page that contained the link. If the page has a <base href> tag, the base is that tag's value, and a crawler must honor it or it will compute wrong addresses.
| Link text | Base | Resolved |
|---|---|---|
| `page2.html` | `https://example.com/docs/a.html` | `https://example.com/docs/page2.html` |
| `/about` | `https://example.com/docs/a.html` | `https://example.com/about` |
| `../x` | `https://example.com/docs/guide/a.html` | `https://example.com/docs/x` |
| `//cdn.example.com/a.js` | `https://example.com/` | `https://cdn.example.com/a.js` |
| `?page=2` | `https://example.com/list` | `https://example.com/list?page=2` |
Python's urllib.parse.urljoin implements these rules.
Normalization steps
Some steps are safe because they never change which resource the URL names. Others are heuristics that work for most sites but can be wrong for some.
| Step | Example | Safe? |
|---|---|---|
| Lowercase scheme and host | `HTTPS://Example.COM` becomes `https://example.com` | Yes |
| Drop default port | `:443` on https, `:80` on http | Yes |
| Remove the fragment | `/a#top` becomes `/a` | Yes, the server never sees fragments |
| Remove dot segments | `/a/./b/../c` becomes `/a/c` | Yes |
| Uppercase percent-escapes, decode unreserved characters | `%7e` becomes `~` | Yes |
| Encode spaces and non-ASCII characters | `a b` becomes `a%20b` | Yes |
| Drop credentials in the URL | `user:pw@host` | Yes for crawling |
| Sort query parameters | `?b=2&a=1` becomes `?a=1&b=2` | Usually |
| Drop tracking parameters | remove `utm_*` | Usually |
| Remove trailing slash | `/docs/` becomes `/docs` | **No** |
| Lowercase the path | `/Docs` becomes `/docs` | **No** |
A normalizer in Python
This function resolves a link against a base, rejects non-web schemes, and applies the safe steps plus two common heuristics: sorting query parameters and dropping tracking parameters.
import re
import string
from urllib.parse import urljoin, urlsplit, urlunsplit, parse_qsl, urlencode, quote
DEFAULT_PORTS = {"http": 80, "https": 443}
UNRESERVED = set(string.ascii_letters + string.digits + "-._~")
def fix_percent(text):
"""Uppercase percent-escapes and decode ones that encode unreserved characters."""
def repl(match):
char = chr(int(match.group(1), 16))
return char if char in UNRESERVED else match.group(0).upper()
return re.sub(r"%([0-9a-fA-F]{2})", repl, text)
def remove_dot_segments(path):
out = []
segments = path.split("/")
for seg in segments[1:]:
if seg == "..":
if out:
out.pop()
elif seg != ".":
out.append(seg)
result = "/" + "/".join(out)
if segments[-1] in (".", "..") and not result.endswith("/"):
result += "/"
return result
def normalize(base, href):
try:
parts = urlsplit(urljoin(base, href.strip()))
scheme = parts.scheme.lower()
host = (parts.hostname or "").lower()
port = parts.port
except ValueError:
return None
if scheme not in DEFAULT_PORTS or not host:
return None
if ":" in host:
host = f"[{host}]" # IPv6 literal
netloc = host
if port and port != DEFAULT_PORTS[scheme]:
netloc = f"{host}:{port}"
path = remove_dot_segments(parts.path or "/")
path = quote(fix_percent(path), safe="/%:@!$&'()*+,;=-._~")
pairs = [
(k, v)
for k, v in parse_qsl(parts.query, keep_blank_values=True)
if not k.lower().startswith("utm_")
]
query = urlencode(sorted(pairs))
return urlunsplit((scheme, netloc, path, query, ""))
base = "https://Example.com:443/docs/guide/index.html"
for href in [
"../intro.html#top",
"HTTPS://EXAMPLE.com/a/./b/../c?utm_source=x&b=2&a=1",
"/search?q=caf%C3%A9&utm_campaign=x",
"/docs/%7Euser/a b",
"mailto:[email protected]",
]:
print(href, "->", normalize(base, href))The script prints:
../intro.html#top -> https://example.com/docs/intro.html
HTTPS://EXAMPLE.com/a/./b/../c?utm_source=x&b=2&a=1 -> https://example.com/a/c?a=1&b=2
/search?q=caf%C3%A9&utm_campaign=x -> https://example.com/search?q=caf%C3%A9
/docs/%7Euser/a b -> https://example.com/docs/~user/a%20b
mailto:[email protected] -> NoneThe function returns None for anything that is not an http or https URL. This covers mailto:, tel:, javascript:, and data: links, and it also covers malformed URLs that raise ValueError.
From links to the frontier
After normalization, the crawler uses the cleaned string as a key. It checks the key against its record of known URLs. If the key is new, the crawler stores it and hands it to the crawl frontier, which the chapter after next explains. If the key is already known, it records the extra link as evidence and moves on. The minimal crawler you saw earlier does this with a seen set. A production system uses a disk-backed store or a probabilistic structure such as a Bloom filter, because the set of known URLs can hold billions of entries.
Edge cases and failure modes
Spider traps. Normalization cannot stop a site from generating an endless supply of different valid URLs. A calendar with a "next month" link, a session ID in the query string, or a relative link that appends a path segment each time (/a/b/a/b/a/b/...) can all create an unbounded URL space. Crawlers defend against this with limits on URL length, path depth, and repeated segments, plus per-host caps.
Fragments and hash-bang routing. Normalization drops fragments because servers never receive them. Single-page applications that route with #/products/5 therefore expose one URL to the crawler, which is one reason such sites are hard to index. The rendering chapter returns to this.
Case and trailing-slash variants. If a site serves the same page at /Docs and /docs, normalization will keep both keys. Duplicate detection has to resolve them later.
Parameter order and meaningless parameters. Sorting parameters merges ?a=1&b=2 with ?b=2&a=1. It cannot know that ?ref=home changes nothing. Some crawlers learn this by fetching variants and comparing results, and site owners can reduce the problem by using clean, consistent internal links.
Internal link consistency. A crawler normalizes mechanically, so it only merges what it can prove is equal. If your pages link to /page, /page/, and /page?ref=nav, the crawler discovers three URLs and spends fetches finding out they are the same.
Scope rules. After normalization, a crawler often decides whether a URL is in scope, for example same host only, as the earlier minimal crawler did with urlparse(absolute).netloc == host. Note that www.example.com and example.com are different hosts under that rule.
Checking your own understanding
Exercise
A crawler's normalizer lowercases the scheme and host, removes default ports, removes fragments, and removes dot segments. It does not touch paths otherwise. Which of these pairs of strings map to the same key? (a) http://Example.com:80/a/./b and http://example.com/a/b (b) https://example.com/Docs and https://example.com/docs (c) https://example.com/a#intro and https://example.com/a#usage
Show answer
Pairs (a) and (c) map to the same key. In (a), the host is lowercased, port 80 is the default for http and is dropped, and ./ is removed, so both become http://example.com/a/b. In (c), the fragments are removed, so both become https://example.com/a. Pair (b) stays different because the path case is preserved. Many servers treat /Docs and /docs as different resources, so the crawler cannot assume they are the same.
Exercise
Why does a crawler normalize a URL before it checks whether the URL is already known?
Show answer
The check compares strings. If HTTPS://Example.com:443/a#top and https://example.com/a were stored as they appear, the crawler would see two unseen URLs, fetch the same page twice, and waste crawl capacity. Normalizing first gives both spellings the same key, so the second one is recognized as already known.