Sub topic 11
Extracting and Tokenizing Page Text
This chapter assumes you can read short Python snippets and know basic HTML structure. By now the crawler has fetched a page, and rendering has produced the final HTML. The next step is to turn that markup into a list of searchable terms. The inverted index in the next chapter is built from this output.
From HTML to text
A fetched page contains much that users never read as content: scripts, styles, and markup. Text extraction keeps the visible words and drops the rest.
An indexer typically does the following:
- Removes
<script>and<style>content. - Reads text from elements such as headings, paragraphs, list items, and link text.
- Records which element each piece of text came from, because a title usually matters more than a footer.
- Separates the main content from repeated boilerplate such as menus and footers, where it can.
Here is a small extractor built on Python's standard HTMLParser.
from html.parser import HTMLParser
class TextExtractor(HTMLParser):
SKIP = {"script", "style"}
def __init__(self):
super().__init__()
self.skip_depth = 0
self.parts = []
def handle_starttag(self, tag, attrs):
if tag in self.SKIP:
self.skip_depth += 1
def handle_endtag(self, tag):
if tag in self.SKIP and self.skip_depth:
self.skip_depth -= 1
def handle_data(self, data):
if not self.skip_depth:
self.parts.append(data)
def extract_text(html):
parser = TextExtractor()
parser.feed(html)
return " ".join(" ".join(parser.parts).split())
html = "<h1>Crawling</h1><script>var x = 1;</script><p>Bots follow links.</p>"
print(extract_text(html))This prints Crawling Bots follow links. The script body is gone, and extra whitespace is collapsed.
Tokenization
Tokenization splits text into tokens, the units the index stores. Most tokens are words. A simple tokenizer lowercases the text and splits on anything that is not a letter or digit.
Most engines also normalize tokens so that different spellings of a word match:
- Case folding.
Crawlandcrawlbecome the same token. - Accent handling.
cafémay be stored ascafe. - Stemming or lemmatization.
crawlingandcrawledreduce to a shared form such ascrawl. - Stop words. Very common words such as
themay be dropped. Many modern engines keep them so that phrase queries still work.
import re
def tokenize(text):
return re.findall(r"[a-z0-9]+", text.lower())
print(tokenize("Bots follow links, then re-crawl pages in 2026."))The output is ['bots', 'follow', 'links', 'then', 're', 'crawl', 'pages', 'in', '2026']. Note that re-crawl becomes two tokens. Splitting on punctuation is a design choice with side effects.
Common errors
- Indexing hidden or script text. Skipping the
SKIPtags avoids filling the index with code. - Using the same tokenizer for indexing and queries. If the index stores stemmed tokens but the query is not stemmed, searches miss pages.
- Ignoring encoding. Decode bytes using the declared charset, or words with accents become garbled tokens.
- Assuming English. The regular expression above drops non-Latin letters. Languages such as Chinese or Japanese do not separate words with spaces and need dedicated segmenters.
- Content missing before rendering. If text is added by JavaScript, extracting from the raw HTML finds nothing. This is why rendering comes first.
Exercise
A page's raw HTML contains <p>Crawlers</p> and the query is "crawler". The index stores unstemmed lowercase tokens. Will the page match, and what change would fix it?
Show answer
It will not match, because crawlers and crawler are different tokens. Apply stemming or lemmatization to both the indexed text and the query so both reduce to crawler.