html, css, and dom · lesson 1 of 8 · sources checked 2026-11-20
from bytes to document: fetch, parse, and text extraction
This lesson follows a response from its bytes to a stored record, and shows what a regex extractor keeps that no user sees.
status of this lesson: documented in my test systempurpose
A collection system must parse the bytes of each response before it can use them. A pipeline with regular expressions and no DOM (Document Object Model) tree is fast and simple. But it keeps text that CSS hides, and it finds nothing on a page that scripts fill.
objectives
- Describe the steps of a fetch and parse pipeline from the response bytes to a stored record.
- Compare a regular-expression extractor with a DOM parser for one task, by cost and by failure modes.
- Explain why a refused source must give an error with its cause, and not an empty list.
- Identify the text that a regular-expression extractor keeps and that no user sees.
new terms
- parse
- To read a document and build a structure from it.
- DOM (Document Object Model)
- The tree of objects that a browser or a parser builds from an HTML document.
- parser
- A program that reads HTML or another format and builds a tree or a list of values.
- extract
- To take data values out of a parsed document.
- crawl
- To fetch pages and follow their links with software.
- robots.txt
- A file at a site root that states crawl rules for automated clients (RFC 9309).
- benchmark platform
- My test system. It runs browsers and tools against test pages and records the result.
- block signature
- A deterministic marker (status, header, cookie, body text) that marks a block when present.
- content hash
- A hash of the content of an item that shows if the content changed.
- soft block
- A response with a normal status that holds no real content or less content.
- render
- To build the visible page from HTML, CSS, and scripts.
how it works
A parser reads a document and builds a structure from it. A browser parser builds a DOM tree. A regular-expression extractor builds no tree. It finds patterns in the text of the response, and it uses them to extract values.
two sources of pages
The pipeline gets pages from two sources:
- A feed. RSS 2.0 puts each entry in an
itemelement. All elements of an item are optional, but an item must have atitleor adescriptionRSS Advisory Board, source 1. Atom is a different XML format, withentryelements RFC Editor, source 2. - A crawler. It starts at the root path, and it can crawl only paths on the same host. It reads the
Disallowrules of the robots.txt file first.
For example, the RSS date Mon, 02 Nov 2026 09:00 GMT and the Atom date 2026-11-03T10:00Z have different forms. The extractor stores each date as it reads it.
the steps of the pipeline
The pipeline of the benchmark platform, my test system, applies these steps to each page that it crawls, in this order:
- A size cap for each page. The pipeline applies it after the full read, so the cap does not protect the memory. A cap on the stream does.
- An early block check. It reads the status and the first 4,000 characters of the body. A hard status, for example 403 or 429, or a block signature marks a block.
- A branch for PDF files. A PDF goes to a text tool, not to the HTML steps.
- The removal of
script,style, and landmark elements such asnav,header, andfooter, with their content. - The removal of all other tags, and the decode of character references such as
&. - The read of the title, the date from a
metatag, and the links. - A content hash of the text, which finds the second copy of a page.
A source that the site refuses gives an error with its cause. It never gives an empty list. An empty list looks like a quiet source, and nobody sees the refusal for a long time.
The block check is not proof of success. A soft block has the status 200 and no real content. Thus a later check must find the real content.
what the standard parser does
The HTML Standard defines the parse rules for each HTML document, also for a document with errors WHATWG, source 3. Thus two browsers that follow it build the same tree from the same bytes.
The standard also gives the order of the sources of the character encoding. When a browser prescans the bytes for a meta charset, the standard encourages it to read only the first 1,024 bytes.
claim of a publisher The documentation of Beautiful Soup shows that different parsers build different trees from one document with errors Beautiful Soup documentation, source 4. For example, the input <a></p> gives three different trees with three parsers.
what a regex extractor cannot see
A regex extractor reads the markup only. It cannot see the style or the layout of the page. Thus text that CSS hides stays in the extracted text. For example, <span style="display:none">Price 99</span> adds "Price 99" to the record.
A page can also render its content in the browser. With client-side rendering, JavaScript changes the DOM after the load Google, source 5. The response text then holds a page with no content, and a regex extractor finds nothing.
estimate, not measured A regex extractor uses less time and less memory than a DOM parser for each page. The difference has no measurement in this course.
the two sides
| automation side | detection side |
|---|---|
| A regex extractor is fast and has no dependency. It cannot see the layout, so hidden text and decoy text go into the data. A source that returns an empty list after a refusal looks quiet. | The site sees only the requests, not the parser. But hidden text and decoy links in the markup get to each client that does not render the page. |
design decisions
| option | gain | cost | when it is correct |
|---|---|---|---|
| Regex extraction with no DOM tree | No dependency, and fast for each page | No style, no layout, and errors when the markup changes | Simple pages of a known form, for example feeds |
| A DOM parser with no render | The same tree that a browser makes from the markup | More time and memory for each page. No style values. | Pages with stable markup and no client-side content |
| A render in a browser | The visible text and the layout | The highest cost for each page | Pages with client-side content, or pages with hidden text |
| A size cap on the stream | The memory stays in its limit | A large valid page fails | Each pipeline |
| An error for a refused source | The refusal shows at once, with its cause | More error records to examine | Each source |
diagram
the fetch and parse pipeline from the response bytes to a stored record
A table of three extraction methods and four things they can see. A regex sees the markup only. A DOM parse with no render sees the markup and the tree. A render in a browser sees the markup, the tree after scripts, the computed style, and the layout.
| method | markup | tree | computed style | layout |
|---|---|---|---|---|
| Regex on the response text | yes | no | no | no |
| DOM parse with no render | yes | yes | no | no |
| Render in a browser | yes | yes, after scripts | yes | yes |
code example
The first example crawls a synthetic site from one file. It obeys the Disallow rules, follows only links on the same host, and extracts text with regular expressions.
example The site, the pages, and the rules are synthetic. The code sends no request.
Crawl a synthetic site from a file. Obey the robots Disallow rules, and follow only paths on the same host. Extract the title, the date, and the text with regular expressions.
import { readFileSync } from "node:fs";
// A synthetic site in one JSON file: { "robots": "...", "pages": { "/path": "<html>" } }.
// The code sends no request. Each page comes from the file.
type Site = { robots: string; pages: Record<string, string> };
function disallowed(robots: string): string[] {
// Only the group "User-agent: *" in this small example.
const rules: string[] = [];
let inGroup = false;
for (const line of robots.split("\n")) {
const [key, ...rest] = line.split(":");
const value = rest.join(":").trim();
if (/^user-agent$/i.test(key.trim())) inGroup = value === "*";
else if (inGroup && /^disallow$/i.test(key.trim()) && value) rules.push(value);
}
return rules;
}
function extract(html: string) {
const title = /<title[^>]*>([^<]*)<\/title>/i.exec(html)?.[1].trim() ?? "";
const date = /<meta[^>]+name="date"[^>]+content="([^"]+)"/i.exec(html)?.[1] ?? "none";
const links = [...html.matchAll(/<a\s[^>]*href="([^"]+)"/gi)].map((m) => m[1]);
const text = html
.replace(/<(head|script|style|nav|header|footer)\b[\s\S]*?<\/\1>/gi, " ")
.replace(/<[^>]+>/g, " ")
.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">")
.replace(/\s+/g, " ").trim();
return { title, date, links, text };
}
const site: Site = JSON.parse(readFileSync(process.argv[2], "utf8"));
const rules = disallowed(site.robots);
const queue = ["/"];
const seen = new Set<string>();
while (queue.length > 0) {
const path = queue.shift()!;
if (seen.has(path)) continue;
seen.add(path);
if (rules.some((r) => path.startsWith(r))) { console.log(`${path}: skip, robots Disallow`); continue; }
const html = site.pages[path];
if (html === undefined) { console.log(`${path}: no page`); continue; }
const page = extract(html);
console.log(`${path}: title "${page.title}", date ${page.date}, text "${page.text}"`);
for (const href of page.links) {
// Same host only: a path that starts with one "/". A scheme or "//" can name a different host.
if (href.startsWith("/") && !href.startsWith("//")) queue.push(href.split("#")[0]);
else console.log(`${path}: one link not followed, other host`);
}
}output
One line for each path: the title, the date, and the text, or the reason to skip it.
/: title "Lab shop", date 2026-11-02, text "Tea & cups Item 1 Admin Partner"
/: one link not followed, other host
/item/1: title "Item 1", date none, text "Price 12 Price 99"
/private/admin: skip, robots DisallowI ran the code with the Node runtime and the flag --experimental-strip-types, on a synthetic site of three pages:
- The root page has a
navelement and the text "Tea & cups". The markup gives the "&" as a character reference. The page links to/item/1,/private/admin, and a page on a different host. - Page
/item/1has a script, the text "Price 12", and the text "Price 99" in aspanwithdisplay:none. - The robots rules disallow
/private/.
The output keeps "Price 99", but no user sees it.
The second example reads stored feed responses. It parses RSS and Atom items, and a keyword gate keeps only the items with a keyword in the title. A refusal gives an error with its cause.
example The feeds and the responses are synthetic.
Parse stored RSS and Atom responses with regular expressions, and keep the items that a keyword gate passes. Give an error with its cause for a refused source.
import { readFileSync } from "node:fs";
// Argument 1: a JSON file of stored feed responses: { "name": { status, body } }.
// Argument 2: a comma-separated list of keywords. The code sends no request.
type Resp = { status: number; body: string };
type Item = { title: string; link: string; date: string };
function tag(block: string, name: string): string {
const m = new RegExp(`<${name}[^>]*>([^]*?)</${name}>`, "i").exec(block);
return m ? m[1].replace(/<!\[CDATA\[|\]\]>/g, "").trim() : "";
}
function parseFeed(xml: string): Item[] {
// RSS 2.0 has <item>. Atom has <entry>, with the link in an href attribute.
const blocks = [...xml.matchAll(/<(item|entry)\b[\s\S]*?<\/\1>/gi)].map((m) => m[0]);
return blocks.map((b) => ({
title: tag(b, "title"),
link: tag(b, "link") || (/<link[^>]+href="([^"]+)"/i.exec(b)?.[1] ?? ""),
date: tag(b, "pubDate") || tag(b, "updated") || "none",
}));
}
function readSource(name: string, r: Resp): Item[] {
// A refusal is an error with its cause. It is never an empty list.
if (r.status < 200 || r.status > 299) throw new Error(`${name}: refused, status ${r.status}`);
if (!/<(rss|feed)[\s>]/i.test(r.body)) throw new Error(`${name}: not a feed, status ${r.status}`);
return parseFeed(r.body);
}
const sources: Record<string, Resp> = JSON.parse(readFileSync(process.argv[2], "utf8"));
const keywords = process.argv[3].toLowerCase().split(",");
for (const [name, r] of Object.entries(sources)) {
try {
const items = readSource(name, r);
const kept = items.filter((i) => keywords.some((k) => i.title.toLowerCase().includes(k)));
console.log(`${name}: items ${items.length}, kept by the keyword gate ${kept.length}`);
for (const i of kept) console.log(` ${i.date} | ${i.title} | ${i.link}`);
} catch (e) {
console.log(`error: ${(e as Error).message}`);
}
}output
One line for each source with its item count and kept count, one line for each kept item, or an error with its cause.
rss1: items 2, kept by the keyword gate 1
Mon, 02 Nov 2026 09:00 GMT | Parser release 2.1 | /news/1
atom1: items 1, kept by the keyword gate 1
2026-11-03T10:00Z | Selector guide | /a/7
error: rss2: refused, status 403
error: rss3: not a feed, status 200I ran the code in the same way, with four synthetic sources and the keywords parser,selector:
- Source rss1 is an RSS feed with two items.
- Source atom1 is an Atom feed with one entry.
- Source rss2 has the status 403 and an HTML page.
- Source rss3 has the status 200 and an HTML page with no feed.
The third example is the early block check. It reads the status and only the first 4,000 characters of the body.
example The markers are synthetic, and no marker describes a real product.
Mark a block from a hard status or from a marker in the first 4,000 characters of the body. Send each other response to the content check.
import { readFileSync } from "node:fs";
// Argument: a JSON file of stored responses: { "name": { status, body } }.
// The markers are synthetic. No marker belongs to a real product.
type Resp = { status: number; body: string };
const HARD_STATUS = [403, 429, 503];
const MARKERS = ["verify-you-are-human", "challenge-form", "access-denied-page"];
const HEAD_CHARS = 4000;
function blockCheck(r: Resp): string {
if (HARD_STATUS.includes(r.status)) return `block: hard status ${r.status}`;
// Read only the start of the body. It is fast, and a block page puts its marker early.
const head = r.body.slice(0, HEAD_CHARS).toLowerCase();
const marker = MARKERS.find((m) => head.includes(m));
if (marker) return `block: marker "${marker}" in the first ${HEAD_CHARS} characters`;
// No block sign is not a success. A later check must find the real content.
return "no block sign: go to the content check";
}
const responses: Record<string, Resp> = JSON.parse(readFileSync(process.argv[2], "utf8"));
for (const [name, r] of Object.entries(responses)) {
console.log(`${name}: ${blockCheck(r)}`);
}output
One line for each response: the block and its cause, or the statement that the content check must decide.
r1: block: hard status 429
r2: block: marker "challenge-form" in the first 4000 characters
r3: no block sign: go to the content check
r4: no block sign: go to the content checkI ran the code in the same way, with four synthetic responses:
- Response r1 has the status 429.
- Response r2 has the status 200 and a form with the class "challenge-form".
- Response r3 has the status 200 and the text "Price 12".
- Response r4 has the status 200 and the marker "verify-you-are-human" after 5,000 characters.
The check does not see the marker of r4. Thus the content check must also find each block that the early check misses.
failure modes
| problem | cause | correction |
|---|---|---|
| A source shows no new items for a long time. | The source returns an empty list after a refusal. | Give an error with its cause for each refusal. Count the refusals of each source. |
| The record holds text that no user sees. | The regex extractor cannot see the style, so hidden text stays. | Render the page, or remove the hidden elements before the extraction. |
| A large page uses all the memory of the worker. | The parse reads the full body before the size cap. | Apply the cap on the stream. |
| The count of successes is too high. | The count uses the HTTP status, not the content. | Count only the pages with real content. |
| The extractor finds no content on a page that a browser shows. | The page renders its content with JavaScript. | Use a render for this page, or read the data source of the page. |
| Two parsers give different values for one page. | The page has markup errors, and the parsers build different trees. | Use a parser that follows the HTML Standard, and test it on the page. |
check questions
Describe the steps of the fetch and parse pipeline, from the fetch of a response to the stored record.
sample answer
The pipeline applies a size cap to each page. Then an early block check reads the status and the first 4,000 characters. A PDF goes to a text branch. For HTML, the pipeline removes the script, style, and landmark elements, strips the other tags, and decodes the character references. Then it reads the title, the date, and the links, and it makes a hash of the text to find copies. A block or an oversize body gives an error record with its cause.
You must extract the item titles from a simple feed of a known form. Which method is correct for this task?
- A render of each feed in a browser, because only a render sees the layout
- A regular-expression extractor, because it is fast, has no dependency, and the feed has no layout
- No extraction, because a feed has no title
answer
b. A regular-expression extractor, because it is fast, has no dependency, and the feed has no layout
A feed of a known form has no style and no layout to read. A regex extractor is fast and has no dependency. A render adds cost and gives nothing for this task.
A feed source returns the status 403. Explain why the code must give an error with its cause, and not an empty list.
sample answer
An empty list looks like a quiet source with no new items. Then nobody sees the refusal for a long time. An error with its cause shows the refusal at once, and the operator can count the refusals of each source.
A page holds a span with the style display:none and the text "Price 99". What does a regex extractor do with this text?
- It keeps the text, because it reads the markup and cannot see the style
- It removes the text, because the style hides it
- It stops with an error
answer
a. It keeps the text, because it reads the markup and cannot see the style
A regex extractor reads only the markup. It cannot see the computed style, so the hidden text goes into the record.
exercise
exercise Do this task in your own lab, with synthetic data only. Do not send a request to a site.
- Save the first code example in an empty folder of your lab.
- Write a JSON file with a robots text that disallows
/hidden/. - Add a root page with links to
/a,/hidden/b, and/c. - Make page
/awith the text "Stock 4" and aspanwithdisplay:noneand the text "Stock 400". - Make page
/cwith afooterelement that holds the text "Contact". - Run the code with Node, the flag
--experimental-strip-types, and the file. - Record the text of each page in the output.
- Write which text of the output no user sees, and why the extractor keeps it.
sample answer
This sample answer uses the synthetic site of the task only.
Path /a gives the text "Stock 4 Stock 400". Path /hidden/b gives "skip, robots Disallow". Path /c gives no "Contact", because the code removes the footer element.
No user sees "Stock 400". The extractor keeps it because it reads the markup only. It cannot see the style display:none. To remove the hidden text, render the page, or remove the hidden elements before the extraction.
sources
- RSS 2.0 Specification, RSS Advisory Board, standard, read 2026-11-20
- RFC 4287: The Atom Syndication Format, RFC Editor, standard, read 2026-11-20
- HTML Standard, parsing, WHATWG, standard, read 2026-11-20
- Beautiful Soup documentation, documentation, read 2026-11-20
- Rendering on the Web, Google, article, read 2026-11-20
- Benchmark platform, code (my test system): the fetch and parse pipeline and its error for a refused source, 2026-11 (not public).
- My model of what each extraction method can see, 2026-11 (not public).