Sub topic 4
Normalizing URLs
This chapter assumes you know basic HTTP, how HTML links work, and how to read short Python programs. It covers how a crawler turns many spellings of a link into one canonical string, so the same page is not fetched twice.
Why normalization matters
A page can be written many ways. These links all point to one page:
HTTP://Example.com:80/about#teamhttp://example.com/about/about(relative, found onhttp://example.com/)
A crawler that compares raw strings sees three different URLs. It fetches the page three times and wastes its politeness budget on one host. Normalization maps equivalent links to a single string. The seen set from the next chapter can then compare plain strings.
The steps
The function below applies each step in order.
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, ''))
print(normalize('http://example.com/a/', '../about#team'))
print(normalize('http://example.com/', 'HTTP://Example.com:80'))
print(normalize('http://example.com/', 'mailto:[email protected]'))The output is:
http://example.com/about
http://example.com/
NoneEach step does one job:
- Resolve.
urljoincombines a relative link with the URL of the page it came from.../abouton/a/becomes/about. - Filter schemes. Only
httpandhttpscan be fetched.mailto:,javascript:andtel:links returnNone. - Lowercase the host. Host names are case-insensitive.
hostnamealready returns lowercase in Python, and the explicitlower()keeps that guarantee visible. - Drop default ports.
:80onhttpand:443onhttpschange nothing, so they are removed. - Give an empty path the value
/.http://example.comandhttp://example.com/are the same request. - Drop the fragment. The part after
#is handled by the browser and never sent to the server.
What this function does not do
Normalization is a trade-off. Each extra rule merges more duplicates, but a wrong rule merges pages that differ.
| Case | Safe to merge? | Why |
|---|---|---|
| `/a?x=1&y=2` and `/a?y=2&x=1` | Usually | Sorting query parameters merges them, but a few servers read order. |
| `/page` and `/page/` | Not always | The server may treat them as different resources. |
| `/Page` and `/page` | No | Paths are case-sensitive on most servers. |
| `?utm_source=news` | Usually | Tracking parameters rarely change content, but you must choose a list. |
| `%7Euser` and `~user` | Yes | Percent-encoding of unreserved characters is equivalent. |
The function above takes the conservative approach. It applies only rules that are always safe. Add the riskier rules one at a time, and only when you see real duplicates in your crawl.
Common errors
- Normalizing before resolving. A relative link has no host to lowercase. Always call
urljoinfirst. - Dropping the query.
?id=7usually selects a different page. Remove only parameters you know are noise. - Forgetting that
parts.portcan raiseValueError. A malformed port such as:abcraises an error. In the full crawl loop, wrap the call or catch the exception so one bad link does not stop the crawl.
Exercise
Using the normalize function with base https://Example.com/blog/, what does the link post?id=3#comments become, and which step removes #comments?
Show answer
It becomes https://example.com/blog/post?id=3. The relative link is resolved against the base, the host is lowercased, and the fragment is dropped by passing an empty string to urlunsplit. The query ?id=3 is kept because it may select a different page.