Sub topic 1
What a Crawler Does and Its Main Components
Prerequisites
This chapter assumes you understand HTTP requests, responses, status codes, and headers. You should also know basic HTML links and Python classes.
A web crawler starts with seed URLs. It downloads each page, finds links, and adds new URLs to a work queue. It repeats this process within limits. A useful crawler separates responsibilities:
- The fetcher makes HTTP requests.
- The parser extracts links from HTML.
- The normalizer turns equivalent links into one URL.
- The frontier stores URLs waiting to be fetched.
- The policy layer applies limits, such as allowed hosts and page budgets.
Fetching Pages
A fetcher should identify itself with a descriptive User-Agent header. It should follow redirects, but record the final URL because that is the page actually received. It should also reject responses that are not HTML and stop reading after a configured size limit.
import urllib.request
def fetch(url, max_bytes=2_000_000):
request = urllib.request.Request(
url,
headers={"User-Agent": "ExampleCrawler/1.0"}
)
with urllib.request.urlopen(request, timeout=10) as response:
if response.headers.get_content_type() != "text/html":
return None
data = response.read(max_bytes)
charset = response.headers.get_content_charset() or "utf-8"
return data.decode(charset, errors="replace")A production fetcher also handles timeouts, connection errors, retry limits, and status codes. Retries should use backoff rather than immediately repeating a failed request.
Extracting Links from HTML
Parse HTML with an HTML parser rather than regular expressions. Collect the href value from each anchor. Resolve relative links against the page URL in a separate normalization step.
from html.parser import HTMLParser
class LinkExtractor(HTMLParser):
def __init__(self):
super().__init__()
self.links = []
def handle_starttag(self, tag, attrs):
if tag == "a":
for name, value in attrs:
if name == "href" and value:
self.links.append(value)Normalizing URLs
Normalization resolves relative paths, accepts only http and https, lowercases the host, removes fragments, and removes default ports. The normalized string becomes the key used for deduplication.
from urllib.parse import urljoin, urlsplit, urlunsplit
def normalize(base, href):
parts = urlsplit(urljoin(base, href))
if parts.scheme not in ("http", "https") or not parts.hostname:
return None
host = parts.hostname.lower()
port = parts.port
default = 80 if parts.scheme == "http" else 443
netloc = host if port in (None, default) else f"{host}:{port}"
return urlunsplit((parts.scheme, netloc, parts.path or "/", parts.query, ""))Exercise
Why should fragments be removed before a URL enters the crawler's seen set?
Show answer
A fragment identifies a location within a page, not a separate HTTP resource, so removing it prevents duplicate fetches.