Sub topic 4
Normalizing URLs
This chapter assumes you know basic HTTP and the parts of a URL (scheme, host, port, path, query, fragment). It also assumes you can read short Python programs. You should already have the crawler's overall shape in mind: fetch a page, extract links, queue new ones.
Why normalization matters
A crawler decides whether it has seen a page by comparing URL strings. Many different strings can name the same page:
http://Example.com:80/ahttp://example.com/a#introhttp://example.com/./a
If the crawler treats these as different, it fetches the same page several times. That wastes bandwidth and storage, loads the target server for no reason, and can produce duplicate entries in your index. Normalization maps every equivalent spelling to one canonical string. The next chapter's seen set then only needs an exact string match.
Normalization is a conservative guess. It should only merge URLs that always return the same content. If it merges two URLs that are actually different pages, the crawler never visits one of them. A missed merge costs a duplicate fetch. A wrong merge loses data.
Where normalization sits
Every link passes through the same steps before it reaches the seen set and the frontier.
The rules
| Rule | Example | Safe? |
|---|---|---|
| Resolve relative links against the page URL | `../c` on `http://a.com/x/y/` becomes `http://a.com/x/c` | Always |
| Keep only `http` and `https` | drop `mailto:`, `javascript:`, `tel:` | Always for a web crawler |
| Lowercase scheme and host | `HTTP://A.COM` becomes `http://a.com` | Always |
| Drop the default port | `:80` for http, `:443` for https | Always |
| Empty path becomes `/` | `http://a.com` becomes `http://a.com/` | Always |
| Remove the fragment | `#section` removed | Always, since fragments never reach the server |
| Remove dot segments | `/a/./b/../c` becomes `/a/c` | Always |
| Normalize percent-escapes | `%7e` becomes `~`, `%2f` becomes `%2F` | Always, if done carefully |
| Sort query parameters, drop tracking ones | `?b=2&a=1&utm_source=x` becomes `?a=1&b=2` | Site-dependent |
| Strip `index.html` or `www.` | Not safe in general |
The last two rows show the line between lossless and lossy rules. The first group changes only the spelling. The query and filename rules assume things about how a particular server behaves.
The basic function
This version resolves, filters, lowercases the host, drops default ports and fragments, and fixes empty paths.
from urllib.parse import urljoin, urlsplit, urlunsplit
def normalize(base, href):
url = urljoin(base, href)
parts = urlsplit(url)
if parts.scheme not in ('http', 'https'):
return None
host = (parts.hostname or '').lower()
if not host:
return None
default_port = 80 if parts.scheme == 'http' else 443
port = parts.port
netloc = host if port in (None, default_port) else f'{host}:{port}'
path = parts.path or '/'
return urlunsplit((parts.scheme, netloc, path, parts.query, ''))A few details are easy to miss:
urljoindoes the relative resolution. It handles../,//host/path, and query-only links like?page=2.urlsplitalready lowercases the scheme.parts.hostnamelowercases the host and removes anyuser:pass@prefix. Rebuilding the netloc from the host and port therefore drops credentials.- The empty-path rule matters because
http://a.comandhttp://a.com/are the same request but different strings.
Gotchas in the basic version
The function above is correct for common links, but real pages expose several weaknesses.
parts.portraisesValueErrorfor a malformed port such ashttp://a.com:abc/. One bad link would crash the crawl.- For an IPv6 host,
hostnamestrips the square brackets. Rebuildingf'{host}:{port}'then produces an invalid URL. - A trailing dot (
example.com.) is a valid, equivalent host name. - Internationalized host names (
bücher.example) have an ASCII form, called punycode, that servers and DNS use. - An absolute
hrefis returned byurljoinwith its path unchanged, so/a/../bis not cleaned. - Percent-escapes have several spellings:
%7e,%7E, and~all mean the same character.
A hardened version
This version fixes each of the weaknesses above. It also strips common tracking parameters and sorts the query, which are optional, site-dependent rules.
import re
from urllib.parse import urljoin, urlsplit, urlunsplit, quote, parse_qsl, urlencode
UNRESERVED = set(
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~'
)
SAFE = "%:@!$&'()*+,;=-._~"
TRACKING = {'gclid', 'fbclid'}
def _unescape(match):
char = chr(int(match.group(1), 16))
return char if char in UNRESERVED else '%' + match.group(1).upper()
def clean_escapes(text):
return re.sub(r'%([0-9a-fA-F]{2})', _unescape, text)
def remove_dot_segments(path):
segments = path.split('/')[1:]
out = []
for seg in segments:
if seg == '.':
continue
if seg == '..':
if out:
out.pop()
continue
out.append(seg)
if segments and segments[-1] in ('.', '..'):
out.append('')
return '/' + '/'.join(out)
def clean_query(query):
pairs = [
(key, value)
for key, value in parse_qsl(query, keep_blank_values=True)
if not key.startswith('utm_') and key not in TRACKING
]
pairs.sort()
return urlencode(pairs)
def normalize(base, href):
try:
parts = urlsplit(urljoin(base, href.strip()))
port = parts.port
except ValueError:
return None
if parts.scheme not in ('http', 'https'):
return None
host = (parts.hostname or '').lower().rstrip('.')
if not host:
return None
if ':' in host:
host = f'[{host}]'
else:
try:
host = host.encode('idna').decode('ascii')
except UnicodeError:
return None
default_port = 80 if parts.scheme == 'http' else 443
netloc = host if port in (None, default_port) else f'{host}:{port}'
path = clean_escapes(quote(parts.path, safe='/' + SAFE))
path = remove_dot_segments(path or '/')
query = clean_query(parts.query) if parts.query else ''
return urlunsplit((parts.scheme, netloc, path, query, ''))
if __name__ == '__main__':
base = 'http://Example.COM/a/b/'
print(normalize(base, '../c/./d?utm_source=x&b=2&a=1#top'))
# http://example.com/a/c/d?a=1&b=2
print(normalize(base, 'HTTP://Example.com:80/x/../y'))
# http://example.com/y
print(normalize(base, '/caf\u00e9'))
# http://example.com/caf%C3%A9
print(normalize(base, '/%7Euser/a%2fb'))
# http://example.com/~user/a%2Fb
print(normalize(base, 'mailto:[email protected]'))
# None
print(normalize(base, 'http://example.com:abc/'))
# NoneThe percent-escape rule decodes only unreserved characters (letters, digits, -._~). It must leave reserved characters such as / encoded. /a%2Fb is a single path segment, while /a/b is two, and servers may treat them differently. For the escapes it keeps, it uppercases the hex digits, so %2f becomes %2F.
Normalization is not full deduplication
Normalization only fixes spelling differences. Some duplicates survive it:
http://a.com/andhttps://a.com/serve the same content. Merging them requires knowing the site supports HTTPS. Redirects usually reveal this at fetch time.a.comandwww.a.commay or may not be the same site./products?id=5and/products/5may be one page behind two routes.- Session IDs in the path or query (
;jsessionid=...,?sid=...) create a new URL on every visit.
Handle these with redirect following, per-site rules, and content-based duplicate detection, which later chapters cover. Session IDs also feed crawl traps, where a site generates unlimited distinct URLs.
Testing normalization
Because the function is pure (same input, same output), it is easy to test. A useful check is idempotence: normalizing an already normalized URL must return it unchanged. If normalize(u, normalize(u, h)) != normalize(u, h), two spellings may still end up in different buckets. Build a test list from real pages you crawl, including odd links such as empty href, href="#", href="//cdn.example.com/x", and href=" /spaced ".
Exercise
A page at https://shop.example/men/shoes/ contains the link ../women/./bags?utm_medium=mail&color=red&size=m#reviews. What does the hardened normalize return, and which rules produced each change?
Show answer
https://shop.example/men/women/bags?color=red&size=m. urljoin resolves ../women against /men/shoes/, which removes the shoes/ segment and gives /men/women/bags. Wait: ../ removes the last directory shoes, so the path is /men/women/bags, and ./ is removed. The utm_medium parameter is dropped as tracking, the remaining parameters are sorted (color before size), and the #reviews fragment is removed. The scheme and host are already lowercase, and the default port is absent, so they are unchanged.
Exercise
Why must normalization leave %2F encoded instead of turning it into /?
Show answer
%2F is a reserved character with a different meaning from a path separator. /a%2Fb is one segment named a/b, while /a/b is two segments. Decoding it could point the crawler at a different resource, or merge two URLs that return different pages.