Sub topic 1
What a Crawler Does and Its Main Components
Prerequisites
This chapter assumes you already know:
- Basic HTTP: requests, responses, status codes, and headers.
- Basic HTML structure, especially how links work.
- Queues, hash sets, and heaps.
- How to read short Python programs.
No crawler experience is needed. This chapter gives the overall picture, and later chapters build each part in detail.
What a crawler does
A web crawler is a program that discovers pages by following links. It starts with a few known addresses, called seed URLs. It downloads each page and pulls out the links. It then downloads the pages those links point to, and repeats until it hits a stopping limit.
Crawlers feed many systems:
- Search engines build an index from crawled pages.
- Archives keep copies of pages over time.
- Price trackers and research tools collect data from a chosen set of sites.
- Link checkers look for broken links on a site.
These uses differ in scale. A link checker for one site fits in a short script. A search engine crawler runs on thousands of machines. The core loop is the same in both, and the engineering effort goes into keeping that loop fast, polite, and bounded.
The core loop
Every crawler repeats the same cycle:
- Take a URL from the list of URLs waiting to be fetched.
- Download the page.
- Parse the page and extract its links.
- Clean up the links and discard any already seen.
- Add the new links to the waiting list.
- Store or process the page, then go back to step 1.
The web is a graph. Pages are nodes and links are edges. A crawler walks that graph, and the waiting list decides the order of the walk.
The main components
URL frontier
The frontier is the data structure that holds URLs waiting to be fetched. It decides which URL comes next. A plain queue gives breadth-first order. A priority queue lets important pages go first. A real frontier also enforces politeness, so it never sends too many requests to one host in a short time. The frontier is the central design decision in a crawler. Later chapters spend a lot of time on it.
Fetcher
The fetcher turns a URL into a response. It sends the HTTP request with a clear User-Agent, follows redirects, sets a timeout, and limits the response size. It also checks the content type, because a crawler that wants HTML should skip images and archives. Network code fails in many ways, so the fetcher is where most error handling lives.
Parser and link extractor
The parser reads the HTML and finds the links, usually the href values of <a> tags. It returns them as the page wrote them. Links are often relative, such as /about or ../next.html, so they cannot be used yet.
URL normalizer
The normalizer resolves a link against the URL of the page that contained it. It then rewrites the result into one standard form. The links HTTP://Example.com:80/a#top and http://example.com/a point to the same page, and normalization makes them the same string. Without this step, the crawler fetches the same page several times.
Seen set
The seen set records every URL the crawler has already queued or fetched. Before a URL enters the frontier, the crawler checks this set. It is usually a hash set at small scale. At large scale it may be a Bloom filter or a disk-backed store, because billions of URLs do not fit in memory.
robots.txt checker
Sites publish a file at /robots.txt that says which paths automated clients may fetch. A well-behaved crawler reads it and obeys it before fetching anything from that host. It caches the file per host so it does not download it for every page.
Storage
Storage keeps what the crawler learned: page content, headers, the fetch time, and sometimes the link graph. It also holds crawler state, such as the frontier and the seen set, so a crash does not lose the work.
A minimal working crawler
The following program runs as shown. It crawls a small fake web held in a dictionary, so there is no network code. It shows how the frontier, the seen set, and the page budget fit together.
from collections import deque
# A fake web: each URL maps to the list of links on that page.
WEB = {
'a': ['b', 'c'],
'b': ['c', 'd'],
'c': ['a'],
'd': [],
}
def fetch(url):
"""Return the page for a URL, or None if it does not exist."""
return WEB.get(url)
def extract_links(page):
"""In this toy web, a page is already its list of links."""
return page
def crawl(seeds, max_pages=10):
frontier = deque(seeds) # URLs waiting to be fetched
seen = set(seeds) # URLs already queued or fetched
fetched = []
while frontier and len(fetched) < max_pages:
url = frontier.popleft()
page = fetch(url)
if page is None:
continue
fetched.append(url)
for link in extract_links(page):
if link not in seen:
seen.add(link)
frontier.append(link)
return fetched
print(crawl(['a'])) # ['a', 'b', 'c', 'd']Three details matter here:
- The URL goes into
seenwhen it is queued, not when it is fetched. If you wait until the fetch, the same URL can be queued many times while it waits in the frontier. - The loop stops when the frontier is empty or the page budget is reached. Page
clinks back toa, so without the seen set this crawl would run forever. poplefton adequemakes the crawl breadth-first. Usingpopinstead would make it depth-first.
The later chapters replace each stub with a real component. Fetching adds HTTP, extraction adds an HTML parser, and normalization cleans the links. The frontier gains per-host queues.
Design goals and their tensions
A crawler has goals that pull against each other.
| Goal | What it means | What it costs |
|---|---|---|
| Throughput | Fetch many pages per second | More concurrency and more load on target sites |
| Politeness | Never overload a host, obey robots.txt | Lower speed per host, more scheduling logic |
| Coverage | Reach as much of the target as possible | More storage, longer crawls |
| Freshness | Keep stored copies close to the live pages | Repeated fetches that compete with discovering new pages |
| Robustness | Survive bad servers, bad HTML, and traps | Limits, timeouts, and extra checks everywhere |
You cannot maximize all of these at once. Raising throughput without regard for politeness gets your crawler blocked. Maximizing coverage without limits lets one endless site consume the whole crawl. A good design states which goals matter most for the job and sets limits to match.
Common mistakes at the design stage
- Treating the frontier as a plain list. A single queue cannot enforce per-host delays. Fixing this later means rewriting the part that everything else depends on.
- Skipping normalization. The seen set only works if equal pages produce equal strings. The same page then gets stored many times.
- No stopping limits. Pages that generate endless links, such as calendars with a "next month" link, never end. Set a page budget and a depth limit from the start.
- No timeouts. One server that accepts a connection and never answers can block a single-threaded crawler forever.
- Ignoring identity. A crawler without a descriptive User-Agent and contact details gives site owners no way to reach you, and they will block you instead.
What comes next
The remaining chapters take the components in this order: fetching, link extraction, normalization, the seen set, and the frontier. They then cover robots.txt, politeness, errors, and concurrency. The final chapters cover traps, content deduplication, storage, recrawling, JavaScript pages, distribution, and monitoring.
Exercise
In the minimal crawler, the URL is added to seen when it is queued, not when it is fetched. Suppose you moved the seen.add(link) call to after the fetch instead. Using the fake web above, which URL would be queued more than once, and why?
Show answer
URL c would be queued twice. Page a links to b and c, and page b links to c. When b is processed, c is still waiting in the frontier and has not been fetched yet, so it is not in seen. The crawler would queue it a second time. The same effect on a real site means the frontier fills with duplicates and pages get fetched repeatedly.
Exercise
Name the component responsible for each task: (1) deciding which URL to fetch next, (2) turning ../next.html into a full URL, (3) checking that a host allows the fetch.
Show answer
(1) The URL frontier. (2) The URL normalizer, which resolves the link against the page URL. (3) The robots.txt checker.