Sub topic 3
Extracting links from HTML
The fetcher gives the crawler a page body. This chapter turns that body into a list of candidate URLs for the frontier. It assumes you can read short Python programs, know basic HTML (tags and attributes), and know what a relative URL is. Normalization and deduplication are covered in the next chapters, so this step only has to produce plausible absolute URLs.
What extraction has to do
Extraction takes the page text and the URL it was fetched from. It returns absolute http and https URLs. It does not fetch anything and does not decide whether a URL is new. Keeping those jobs apart makes each one easy to test.
The work has four steps:
- Parse the HTML and collect the raw attribute values that point to other documents.
- Work out the base URL that relative values resolve against.
- Resolve each value into an absolute URL.
- Drop values the crawler cannot or should not follow.
Which tags carry links
Anchor tags are the main source, but not the only one.
| Tag and attribute | Meaning | Usually followed? |
|---|---|---|
| `a href` | Ordinary hyperlink | Yes |
| `area href` | Clickable region of an image map | Yes |
| `frame src`, `iframe src` | Embedded document | Yes, if you want embedded content |
| `link href` | Stylesheets, canonical URL, feeds | Only for specific `rel` values |
| `img src`, `script src` | Resources, not pages | No, for a page crawler |
A crawler that only indexes text pages can start with a, area, frame and iframe. Add link rel="canonical" later if you want to use it for duplicate detection.
Use a real parser, not a regular expression
A pattern such as href="(.*?)" fails on many inputs that are common in real pages:
- Single-quoted and unquoted values:
href='/x'andhref=/x. - Uppercase tags and attributes:
<A HREF=...>. - Links inside comments,
<script>blocks, or<textarea>text, which are not links. - Entities in the value:
href="/search?a=1&b=2"must become/search?a=1&b=2.
The standard library HTMLParser handles all of these. It lowercases tag and attribute names, unescapes entities in attribute values, and does not report text inside comments as tags. It is also tolerant of broken markup. It never raises on unclosed tags, so one bad page cannot stop the crawl. For heavy workloads, lxml or selectolax are faster, but the logic is the same.
A fuller extractor
The basic version from the outline collects every a href. The version below also reads <base>, skips links marked rel="nofollow", records a page-level nofollow robots meta tag, and handles area and frames. It collects raw values first and resolves them after parsing, because a <base> tag can appear after some links in a badly written page. Browsers use the first <base href>, so the code does too.
from html.parser import HTMLParser
from urllib.parse import urldefrag, urljoin
class LinkExtractor(HTMLParser):
def __init__(self):
super().__init__()
self.base_href = None
self.raw_links = []
self.nofollow_page = False
def handle_starttag(self, tag, attrs):
a = dict(attrs)
if tag == 'base':
if self.base_href is None and a.get('href'):
self.base_href = a['href'].strip()
elif tag == 'meta':
if (a.get('name') or '').lower() == 'robots':
if 'nofollow' in (a.get('content') or '').lower():
self.nofollow_page = True
elif tag in ('a', 'area'):
self._add(a.get('href'), a.get('rel'))
elif tag in ('frame', 'iframe'):
self._add(a.get('src'), None)
def _add(self, value, rel):
if not value:
return
if 'nofollow' in (rel or '').lower().split():
return
self.raw_links.append(value.strip())
def extract_links(page_url, html):
parser = LinkExtractor()
parser.feed(html)
parser.close()
if parser.nofollow_page:
return []
base = urljoin(page_url, parser.base_href) if parser.base_href else page_url
links = []
for raw in parser.raw_links:
absolute = urldefrag(urljoin(base, raw))[0]
if absolute.startswith(('http://', 'https://')):
links.append(absolute)
return links
html = '''<html><head><base href="/docs/"><meta name="robots" content="index"></head>
<body>
<a href="intro.html">Intro</a>
<a href=" ../about ">About</a>
<a href="mailto:[email protected]">Mail</a>
<a href="javascript:void(0)">Script</a>
<a href="https://other.example/x" rel="nofollow">Ad</a>
<a href="#top">Top</a>
<area href="map.html">
<a href>Empty</a>
</body></html>'''
for link in extract_links('https://example.com/blog/post', html):
print(link)Running it prints:
https://example.com/docs/intro.html
https://example.com/about
https://example.com/docs/
https://example.com/docs/map.htmlThe mailto: and javascript: values are dropped by the scheme check. The nofollow link and the attribute with no value are skipped. The #top link resolves against the base, not the page, so it becomes the /docs/ URL. Browsers behave the same way.
Edge cases to plan for
Whitespace. Browsers strip leading and trailing whitespace from href values, so the extractor should too. Without the strip(), " ../about " would resolve to a URL containing spaces.
Fragments. /page#section1 and /page#section2 are the same document to a server. The fragment never reaches the server. Removing it during extraction means the seen set does not hold both.
Schemes. urljoin returns mailto:, tel:, data: and javascript: values unchanged. Filter by scheme after resolving, not before. A value such as //cdn.example/x has no scheme until urljoin adds one from the base.
Character encoding. HTMLParser.feed takes str, so decode the bytes first. Use the charset from the Content-Type header, and fall back to UTF-8 with errors='replace', as the fetch function in this tutorial does. A wrong guess garbles non-ASCII characters in URLs, which then become different URLs.
Duplicate attributes. If a tag repeats an attribute, dict(attrs) keeps the last value, while browsers keep the first. This is rare, and you can ignore it unless you need exact browser fidelity.
Huge link lists. Some pages contain tens of thousands of links, often generated. The size cap on the fetch limits the damage. You can also cap links per page, for example at 5,000, and log when the cap is hit.
Nofollow. rel="nofollow" and the robots meta tag are hints from the site owner. A polite crawler honors them if it calls itself a search crawler. A link checker or archiver may reasonably ignore them. Make this a documented setting, not an accident.
Common errors
- Resolving against the final URL after redirects is correct. Resolving against the originally requested URL is not. If
/aredirects to/b/c, relative links on that page are relative to/b/c. Pass the final URL from the fetcher intoextract_links. - Forgetting
<base>creates wrong URLs on the pages that use it. These URLs usually return 404, and the cause is hard to see in logs. - Keeping
javascript:links wastes frontier space and may cause errors in the fetcher. - Skipping
parser.close()can lose a trailing partial tag in truncated pages, which is common when you cap the download size.
Exercise
A page fetched from https://example.com/a/b/page.html contains no base tag and the link <a href="../x?id=1#top">. What absolute URL should the extractor emit, and why does it drop the #top part?
Show answer
It emits https://example.com/a/x?id=1. The .. removes the b directory from the base path, and the query string stays. The fragment is dropped because it is handled only by the browser and never sent to the server, so keeping it would make the same document look like several different URLs.
Exercise
Why does the extractor collect raw href values first and resolve them after parsing, instead of resolving each one as it is seen?
Show answer
A <base href> tag can appear after some links in the document. If links were resolved immediately, those earlier links would use the wrong base. Collecting raw values and resolving after feed and close guarantees the base is known for every link.