Sub topic 4
Parsing HTML and Extracting Links
This chapter covers how a crawler turns a fetched HTML document into a list of candidate URLs. It assumes you know what an HTTP response looks like, can read basic HTML, and can follow short Python snippets. Fetching comes before this stage, and URL normalization comes after it. Here we focus on the step between them: reading markup and pulling out links.
Where link extraction fits
A fetch returns bytes. The crawler must decode those bytes into text, parse the text into a structure, and find the places where the page points to other resources. Each pointer it finds is a candidate URL. Candidates then go to the discovery and normalization stage, and from there into the crawl frontier.
Extraction is a separate step from indexing. The same parsed document usually feeds both the link extractor and the text extractor, but they answer different questions. The link extractor asks where else the crawler can go. The text extractor asks what the page says.
Decoding the bytes first
HTML arrives as bytes. The crawler picks a character encoding from several signals, roughly in this order:
- A byte order mark at the start of the file.
- The
charsetparameter in theContent-Typeresponse header. - A
<meta charset>declaration near the top of the document. - A guess based on the byte patterns.
If the crawler guesses wrong, link text and any non-ASCII characters in URLs become garbage. A wrong guess rarely breaks plain ASCII links, which is why the bug often goes unnoticed until a site with accented paths is crawled.
Also check the Content-Type header before parsing. A response of application/pdf or image/png should not be fed to an HTML parser. Crawlers use the header, and sometimes sniff the first bytes, to decide whether to parse a response as HTML at all.
Parsers must tolerate broken markup
Real pages contain unclosed tags, mismatched nesting, and stray characters. Browsers repair these in a standardized way, and crawlers need to be at least as forgiving. A strict XML parser will reject many real pages. An HTML parser that follows the HTML parsing rules will recover and still expose the links.
Python's html.parser.HTMLParser is event-based. It calls a method each time it sees a start tag, an end tag, or text. It does not build a tree, so it uses little memory and works well for simple extraction.
Which elements carry links
The <a href> element is the main source, but it is not the only one.
| Element or attribute | What it points to | Typical crawler use |
|---|---|---|
| `<a href>` | Another page or resource | Primary discovery of pages |
| `<link rel="canonical" href>` | The preferred URL for this content | Input to canonicalization |
| `<link rel="alternate" href>` | A translation or other version | Discovery of related versions |
| `<link rel="next">` and `rel="prev"` | Adjacent pages in a series | Sometimes used as a discovery hint |
| `<img src>`, `<script src>`, `<link rel="stylesheet" href>` | Sub-resources | Needed for rendering, not page discovery |
| `<iframe src>` | An embedded document | May be fetched as part of the page |
| `<base href>` | A new base for relative URLs | Changes how every other link resolves |
Crawlers separate links to pages from links to resources used to display a page. A page link is a candidate for indexing. A sub-resource link matters when the crawler renders the page, which a later chapter covers.
Resolving relative links
Many href values are relative, such as /about, ../contact, or ?page=2. They only make sense against a base URL. The base is normally the URL of the page that contained the link. If the document has a <base href> element, that value replaces it.
Python's urllib.parse.urljoin implements the standard resolution rules.
from urllib.parse import urljoin
page = "https://example.com/blog/posts/intro.html"
print(urljoin(page, "/about"))
print(urljoin(page, "../archive/"))
print(urljoin(page, "?page=2"))
print(urljoin(page, "//cdn.example.com/lib.js"))
print(urljoin(page, "https://other.example.org/"))The output is:
https://example.com/about
https://example.com/blog/archive/
https://example.com/blog/posts/intro.html?page=2
https://cdn.example.com/lib.js
https://other.example.org/Note the fourth case. A value starting with // is a scheme-relative URL. It keeps the page's scheme and replaces the host.
A link extractor that handles the details
The simple parser in a basic crawler collects every href on an <a> tag. A more careful version also honors <base href>, ignores non-web schemes, and records the rel attribute so later stages can see nofollow.
from html.parser import HTMLParser
from urllib.parse import urljoin, urldefrag, urlparse
class LinkExtractor(HTMLParser):
def __init__(self, page_url):
super().__init__()
self.page_url = page_url
self.base_url = page_url
self.links = [] # list of (absolute_url, rel)
def handle_starttag(self, tag, attrs):
attr = dict(attrs)
if tag == "base" and attr.get("href"):
# Only the first base element counts, and it applies to all links.
if self.base_url == self.page_url:
self.base_url = urljoin(self.page_url, attr["href"])
elif tag == "a" and attr.get("href"):
self._add(attr["href"], attr.get("rel", ""))
def _add(self, href, rel):
href = href.strip()
absolute, _ = urldefrag(urljoin(self.base_url, href))
if urlparse(absolute).scheme in ("http", "https"):
self.links.append((absolute, rel.lower()))
html = """
<html><head><base href="https://example.com/docs/"></head>
<body>
<a href="intro.html#top">Intro</a>
<a href="mailto:[email protected]">Email</a>
<a href="javascript:void(0)">Menu</a>
<a href="https://other.example.org/" rel="nofollow">Partner</a>
</body></html>
"""
extractor = LinkExtractor("https://example.com/index.html")
extractor.feed(html)
for url, rel in extractor.links:
print(url, rel or "-")This prints:
https://example.com/docs/intro.html -
https://other.example.org/ nofollowThree things happened. The <base> element changed how intro.html resolved. The fragment #top was removed because a fragment is never sent to the server. The mailto: and javascript: links were dropped because they are not fetchable web URLs.
The <base> handling above assumes the element appears before the links that depend on it. That matches how browsers behave, since <base> belongs in the <head>. A crawler that builds a full tree first can find the base element anywhere and then resolve all links.
The `rel` attribute
The rel attribute describes the relationship between the current page and the target. Values you will meet when crawling:
nofollow: the page author does not vouch for the target. Search engines treat it as a hint about how to use the link, and treatment varies.sponsored: the link is paid or an advertisement.ugc: the link comes from user-generated content such as comments.noopenerandnoreferrer: browser security behaviors. They have no bearing on crawling.
The attribute can hold several space-separated values, such as rel="nofollow noopener". Splitting on whitespace is safer than comparing the whole string. The extractor above stores the raw string, so a later stage should split it.
The page-level equivalent is <meta name="robots" content="nofollow">, which applies to every link on the page. The indexing controls chapter returns to it.
Edge cases that break naive extractors
Several situations cause real crawlers to miss links or collect bad ones.
- Links created by JavaScript. If the page builds its links after loading, they are absent from the raw HTML. The parser sees an empty container. Finding them requires rendering the page.
- Click handlers without an
href. A<button onclick="...">or a<div>with a handler does not expose a URL. A crawler that only readshrefcannot follow it. Using a real<a href>is the dependable way to make a destination discoverable. - Empty and placeholder hrefs. Values like
#,"", andjavascript:void(0)resolve to the current page or to nothing useful. Filter them. - Whitespace and entities. An
hrefcan contain leading spaces or HTML entities such as&. A real parser decodes entities for you.HTMLParserdoes so by default withconvert_charrefs=True. - Very long or malformed URLs. Some pages emit thousands of characters or invalid syntax. Crawlers set a maximum length and discard anything that fails to parse.
- Infinite link spaces. A calendar with a "next month" link can generate endless URLs. Extraction cannot detect this. The frontier and crawl budget chapters cover the defenses.
- Large documents. A crawler caps how many bytes it reads from one response and sometimes how many links it keeps per page. Links near the end of a very large page may never be seen.
Anchor text
The visible text inside an <a> element is called anchor text. It describes the target in the author's words, so search engines record it and associate it with the destination URL. To capture it, an event-based parser must track when it is inside an anchor and collect text events until the closing tag. Keep this in mind when you design a record for each link: source URL, target URL, rel, and anchor text.
Testing your extractor
Check an extractor against pages you control before trusting it. Cases worth covering are a relative path with .., a <base> element, a fragment-only link, a non-web scheme, and an entity in a query string.
sample = '<a href="/search?q=a&page=2">next</a>'
ex = LinkExtractor("https://example.com/")
ex.feed(sample)
print(ex.links)This prints [('https://example.com/search?q=a&page=2', '')]. The & was decoded to & before the URL was resolved. If you see & in your output, the entity was not decoded, and the crawler would request a different URL from the one the author intended.
Summary
Link extraction decodes the response, parses the markup tolerantly, collects URLs from the relevant elements, resolves them against the correct base, and discards anything that is not a fetchable web URL. The output is a list of candidates, not a final list of pages to crawl. Normalization, deduplication, robots.txt checks, and prioritization all happen afterward.
Exercise
A page at https://example.com/shop/items/list.html contains <a href="../cart"> and <a href="//static.example.com/app.js">. What absolute URLs do these resolve to, and what would change if the page's head contained <base href="https://example.com/store/">?
Show answer
Without a base element, ../cart resolves to https://example.com/shop/cart and the second link resolves to https://static.example.com/app.js, because a leading // keeps the scheme and replaces the host. With the base element, relative links resolve against https://example.com/store/, so ../cart becomes https://example.com/cart. The scheme-relative link is unchanged, since it supplies its own host.
Exercise
Why does a crawler that reads only the raw HTML miss a link added by JavaScript after the page loads, and why is a <div onclick="go()"> a poor way to expose a destination?
Show answer
The raw HTML does not contain the link, because the script creates it later. The crawler would need to render the page to see it. A <div> with a click handler has no href, so there is no URL for an extractor to read. A real <a href> element exposes the destination in the markup.