Sub topic 11
Extracting and Tokenizing Page Text
This chapter assumes you can read short Python snippets and know basic HTML. You should also know that earlier stages have already fetched the page, rendered it if needed, and settled on a canonical URL. Here you will turn the HTML into the terms the index stores.
Where this stage sits
Rendering and canonicalization leave the pipeline with one HTML document per canonical URL. The inverted index, covered in the next chapter, needs something simpler: a list of normalized terms, each with a position and the field it came from. Text extraction and tokenization produce that list.
Decoding bytes into text
A response body is bytes. Before parsing, the crawler must pick a character encoding. It checks the charset parameter of the Content-Type header first, then a <meta charset> tag, and finally falls back to a default or a guess. A wrong choice produces mojibake such as café instead of café, and those garbage terms never match real queries.
import re
def decode(body: bytes, content_type: str) -> str:
match = re.search(r"charset=([\w-]+)", content_type, re.I)
charset = match.group(1) if match else "utf-8"
try:
return body.decode(charset, errors="replace")
except LookupError:
return body.decode("utf-8", errors="replace")errors="replace" keeps one bad byte from discarding the whole page.
Extracting visible text
Extraction keeps the text a reader would see and drops the rest. The rules are:
- Skip the contents of
script,style,noscript, andtemplate. They hold code or fallback content, not page content. - Treat block-level tags (
p,div,li, headings) as word boundaries. Without this,<p>Hello</p><p>world</p>becomesHelloworld. - Do not add a boundary for inline tags such as
borem.<b>Cr</b>èmeis one word. - Decode entities, so
&becomes&. - Keep useful attribute text, such as an image's
alt. - Record the title separately, because matches in the title usually count for more than matches in the body.
import re
import unicodedata
from html.parser import HTMLParser
class TextExtractor(HTMLParser):
SKIP = {"script", "style", "noscript", "template"}
BLOCK = {"p", "div", "br", "li", "tr", "td", "section", "article",
"nav", "header", "footer", "h1", "h2", "h3", "h4", "h5", "h6"}
def __init__(self):
super().__init__() # convert_charrefs=True decodes entities
self.skip_depth = 0
self.in_title = False
self.title_parts = []
self.body_parts = []
def handle_starttag(self, tag, attrs):
if tag in self.SKIP:
self.skip_depth += 1
elif tag == "title":
self.in_title = True
elif tag == "img" and not self.skip_depth:
alt = dict(attrs).get("alt")
if alt:
self.body_parts.append(" " + alt + " ")
if tag in self.BLOCK:
self.body_parts.append(" ")
def handle_endtag(self, tag):
if tag in self.SKIP and self.skip_depth:
self.skip_depth -= 1
elif tag == "title":
self.in_title = False
if tag in self.BLOCK:
self.body_parts.append(" ")
def handle_data(self, data):
if self.skip_depth:
return
(self.title_parts if self.in_title else self.body_parts).append(data)
def result(self):
def clean(parts):
return re.sub(r"\s+", " ", "".join(parts)).strip()
return clean(self.title_parts), clean(self.body_parts)
def tokenize(text):
text = unicodedata.normalize("NFKC", text).casefold()
return re.findall(r"\w+(?:['’]\w+)*", text)
html = """<html><head><title>Café Guide</title>
<style>p{color:red}</style></head><body>
<nav>Home | About</nav><h1>Coffee & Tea</h1>
<p>Don’t miss the <b>Crème</b> brûlée.</p>
<script>var x = "hidden";</script>
<img src="a.jpg" alt="Espresso machine"></body></html>"""
extractor = TextExtractor()
extractor.feed(html)
title, body = extractor.result()
print(tokenize(title))
print(list(enumerate(tokenize(body))))The first line prints ['café', 'guide']. The second prints the body tokens with their positions: home, about, coffee, tea, don’t, miss, the, crème, brûlée, espresso, machine, numbered 0 to 10. The CSS and the script text are gone. The & is gone because it is not a word character. The navigation words home and about are still there.
Tokenizing
A token is the unit the index stores. Tokenization decides what counts as a word, and it needs several decisions.
Normalization
- Case folding.
casefold()makesCoffeeandcoffeethe same term. It is stronger thanlower()for some languages (Germanßbecomesss). - Unicode normalization. The same visible
écan be one character oreplus a combining accent. NFKC maps both to one form. Without it, a query typed on one keyboard misses text written on another. - Accent folding. Mapping
cafétocaferaises recall but merges distinct words in some languages. Do it per language. Stripping every combining mark would damage scripts where those marks are part of the letters.
Splitting
Splitting on non-word characters handles English well. Edge cases need explicit choices:
| Input | Naive result | Common decision |
|---|---|---|
| `don’t` | `don`, `t` | Keep as one token (the regex above does) |
| `state-of-the-art` | four tokens | Split, and possibly also index the joined form |
| `3.14`, `1,000` | split at punctuation | Keep numbers whole |
| `[email protected]` | three tokens | Special rules, or accept the split |
| Chinese or Japanese text | one huge token | Needs a word segmenter or character n-grams, because there are no spaces |
Stop words and stemming
A stop word is a very common word such as the or of. Dropping stop words shrinks the index but breaks phrase queries like "to be or not to be". Many modern engines keep them. Stemming reduces crawling and crawled to a shared stem like crawl. This improves recall and adds false matches, and it is language specific.
What to keep besides the term
A bare term is rarely enough. The index entry for each token usually records:
- Position, the token's offset in the document. Phrase queries such as "web pages" need it to check that two words are adjacent.
- Field, such as title, heading, body, or image alt text. Ranking can weight fields differently.
- Frequency, derived by counting a term's occurrences in a document.
Common errors
- Indexing
scriptandstyletext, which makes JavaScript variable names searchable. - Joining words across block tags, which creates terms like
helloworld. - Decoding with the wrong charset, which fills the index with mojibake terms.
- Using different normalization at index time and query time.
- Indexing text hidden to deceive crawlers. Engines try to detect and discount it, so treat it as a risk, not a technique.
- Expecting text to be extracted from a JavaScript-built page that was not rendered. The extractor can only read what rendering produced.
Exercise
A site indexes Crème as crème using casefold() only. A user searches for CRÈME, typed with a combining accent (E followed by U+0300 and then ME), and gets no results. Which tokenization step is missing, and where must the fix be applied?
Show answer
Unicode normalization (NFKC) is missing. The query's accented letter is a different sequence of code points from the one in the index, so the strings do not match even after case folding. The same normalization must run on both documents at index time and queries at search time, and the index must be rebuilt if the document-side pipeline changes.
Exercise
In the extractor, why does handle_starttag append a space for block tags such as p, but not for b?
Show answer
Block tags separate words visually, so without a space <p>Hello</p><p>world</p> would produce the single token helloworld. Inline tags like b can sit inside a word (<b>Cr</b>ème), so adding a space there would split one word into two tokens.