05.3 Parsing HTML, Web Pages and Office Files
Most of the world's useful text is not in a tidy text file. It sits inside web pages wrapped in navigation and advertising, inside Word documents with tracked changes and footnotes, inside spreadsheets where the meaning lives in merged cells, inside email threads with quoted replies, inside slide decks where the presenter notes matter more than the bullets, and inside structured records that are almost — but not quite — documents. Before any of that text can be chunked, embedded and retrieved, something has to turn each file into clean, faithful text with its structure intact. This lesson is that something: the complete engineering guide to parsing HTML, fetching web pages properly, and extracting text from Office files, email, ebooks, structured data, code and transcripts — with the parsers verified as of November 2026, the decision tables that tell you which tool to reach for, and the failure gallery of what goes wrong in production.
What you'll learn
- How HTML works as a tree (the DOM), why parsers behave like browsers, and how malformed HTML and encodings are handled
- The HTML parsing toolbox:
html.parserin the standard library, BeautifulSoup4,lxml,html5lib,selectolax, CSS and XPath selectors, and what each is good at - Main-content extraction: boilerplate and invisible-element removal with
trafilatura,readability-lxmlandjustext, and when to write your own rules instead - HTML → Markdown with
markdownify,html2textand friends, and how to keep headings, lists, tables, code blocks and links faithful - Metadata extraction:
<title>, canonical URLs,<html lang>, OpenGraph, JSON-LD and Dublin Core viaextruct, dates viahtmldate - Fetching the web properly:
httpx(sync and async), conditional requests withETag/Last-Modified,robots.txtviaurllib.robotparserandprotego, page-levelnoindex/nofollowdirectives, rate limiting, retries, URL canonicalization withw3libandcourlan, crawl scope and depth, and JS-rendered pages with Playwright - Documentation sources that beat scraping: sitemaps,
llms.txt, Markdown versions of pages, RSS/Atom feed autodiscovery, GitHub repositories and OpenAPI specs - Markup formats: Markdown, reStructuredText, AsciiDoc and LaTeX, with Pandoc as the universal converter
- Office files:
.docxwithpython-docx(and its limits: comments, tracked changes, footnotes),.xlsxwithopenpyxland pandas,.pptxwithpython-pptx, legacy.doc/.xls/.pptvia LibreOffice headless, ODF and RTF - The multi-format front doors: Pandoc 3.13, Microsoft MarkItDown, IBM Docling, Unstructured, and Apache Tika — what each gives you, what it hides, and its licence
- Encrypted Office files with
msoffcrypto-tool, and why you never brute-force a password - Email (
.eml, MBOX,.msg), EPUB ebooks, and Google Docs/Sheets export formats - Structured data: CSV/TSV, JSON/JSONL including nested-JSON flattening, XML with
defusedxml, YAML, Parquet, and SQL rows turned into text - Code repositories and Jupyter notebooks as ingestion sources
- Transcripts and chat logs: subtitles (SRT/VTT), meeting transcripts, Slack/Teams exports and threads
- The parser layer itself: a registry mapping file types to parsers, content-based type detection, size limits, timeouts, per-file error isolation, zip-bomb hygiene, archive/container unpacking with depth limits, and mapping everything into the
ParsedDocumentmodel from 05.2
What you don't need
- Any API keys or model calls. Everything here is local parsing; the only place a model enters is a short preview of sending hard pages to a vision model, which links to 03.6 for the mechanics.
- A running browser or any installed software beyond Python. Playwright is shown but you don't need to install its browsers to learn the code; Pandoc and LibreOffice are external tools we invoke from the shell.
- Knowledge of the
ParsedDocumentmodel internals — 05.2 defines it; this lesson shows how your parsers feed it. - Chunking, cleaning, metadata schemas, embeddings or pipeline orchestration. Those are 05.5, 05.6, 05.8 and 05.9; this lesson stops where the parser hands off clean text.
Setup
You need Python 3.11+ (3.13 is recommended for this module: one of the big parsers, unstructured, does not support Python 3.14 as of November 2026). First time? Create a project with uv init data-pipeline --bare --python 3.13 && cd data-pipeline, then install this lesson's core libraries:
uv add beautifulsoup4 lxml selectolax soupsieve \
trafilatura readability-lxml justext \
markdownify httpx w3lib courlan htmldate \
extruct protego charset-normalizer tenacity \
defusedxml nh3 filetype
# or: pip install beautifulsoup4 lxml selectolax ...These commands install the newest release of each package. The samples were written and checked against the releases current as of November 2026 (for example beautifulsoup4 4.15.0, lxml 6.1.3, trafilatura 2.3.1, docling 2.147.0 and unstructured 0.27.36); each script's # needs: header comment names the packages it imports. Fast-moving parsers such as docling, unstructured and markitdown change output shape between releases, and a newer major version may rename things, so check the library's changelog if a sample does not match.
Each part adds its own extras, so you only install what you're reading:
# Part 3 (web fetching, JS rendering)
uv add playwright
playwright install chromium # downloads a browser; skip if you only read
# Part 4-5 (docs sites, markup formats)
uv add markdown-it-py docutils mistune python-frontmatter
# Part 6 (Office files and universal converters)
uv add python-docx openpyxl pandas python-pptx \
mammoth msoffcrypto-tool markitdown docling \
unstructured
# external tools: Pandoc 3.13 (https://pandoc.org) and LibreOffice 26.x
# (https://www.libreoffice.org) — installed separately, called from the shell
# Part 7 (email, EPUB)
uv add mail-parser extract-msg ebooklib striprtf
# Part 8-10 (structured data, notebooks, feeds)
uv add pyyaml pyarrow nbformat feedparserSample data
The Office, email, ebook, notebook and structured-data examples read files from a small data/ corpus. Build it once with this script (run from the project root, after the Part 6–9 installs — the PDF/CSV/JSONL/email parts are stdlib-only):
# make_sample_data.py — builds the data/ corpus used across Parts 6-11.
# Run once: uv run python make_sample_data.py (or: python make_sample_data.py)
# Everything is fictional ("Acme") and deterministic — re-running overwrites.
import csv
import json
import pathlib
import shutil
import subprocess
ROOT = pathlib.Path("data")
(ROOT / "uploads").mkdir(parents=True, exist_ok=True)
(ROOT / "assets").mkdir(parents=True, exist_ok=True)
def write_pdf(path: pathlib.Path, title: str, lines: list[str]) -> None:
"""Minimal valid one-page PDF (stdlib only) — enough for file-type
detection and 'does the pipeline open it' checks."""
def esc(s: str) -> str:
s = s.encode("latin-1", "replace").decode("latin-1")
return s.replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)")
stream = "BT /F1 18 Tf 72 720 Td (%s) Tj ET\n" % esc(title)
y = 692
for ln in lines:
stream += "BT /F1 11 Tf 72 %d Td (%s) Tj ET\n" % (y, esc(ln))
y -= 16
data = stream.encode("latin-1")
objs = [
b"<< /Type /Catalog /Pages 2 0 R >>",
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] "
b"/Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>",
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
b"<< /Length %d >>\nstream\n" % len(data) + data + b"endstream",
]
out = bytearray(b"%PDF-1.4\n")
offsets = []
for i, obj in enumerate(objs, 1):
offsets.append(len(out))
out += b"%d 0 obj\n" % i + obj + b"\nendobj\n"
xref = len(out)
out += b"xref\n0 %d\n" % (len(objs) + 1)
out += b"0000000000 65535 f \n"
for off in offsets:
out += b"%010d 00000 n \n" % off
out += (b"trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n"
% (len(objs) + 1, xref))
path.write_bytes(bytes(out))
def write_tiny_png(path: pathlib.Path) -> None:
"""1x1 red PNG (stdlib only) — a stand-in logo for the pptx sample."""
import struct
import zlib
def chunk(tag: bytes, data: bytes) -> bytes:
return (struct.pack(">I", len(data)) + tag + data +
struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF))
ihdr = struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0)
idat = zlib.compress(b"\x00\xff\x00\x00") # filter byte + one red RGB pixel
path.write_bytes(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) +
chunk(b"IDAT", idat) + chunk(b"IEND", b""))
# --- PDFs: handbook.pdf feeds Docling in 6.6; report.pdf feeds
# Unstructured in 6.6 and the filetype probe in 11.1 ---
write_pdf(ROOT / "handbook.pdf", "Acme Product Handbook",
["Getting started", "Install the CLI and run `acme init`.",
"Plans: Pro 10 seats $200/yr, Team 50 seats $800/yr."])
write_pdf(ROOT / "report.pdf", "Q3 Data Pipeline Report",
["Parsing coverage: PDF, HTML, Office, email, structured.",
"Cleaning, chunking and metadata land in 05.5-05.8."])
write_pdf(ROOT / "uploads" / "report", "Mystery upload",
["No extension on purpose — 11.1 detects it by magic bytes."])
# --- Word: handbook.docx (6.2) + report.docx (6.6) ---
from docx import Document
doc = Document()
doc.core_properties.title = "Acme Product Handbook"
doc.core_properties.author = "Jane Doe"
doc.add_heading("Getting started", level=1)
doc.add_paragraph("Install the CLI and run `acme init`.")
table = doc.add_table(rows=2, cols=3)
for i, row in enumerate([["Plan", "Seats", "Price"],
["Pro", "10", "$200"]]):
for j, val in enumerate(row):
table.rows[i].cells[j].text = val
doc.add_heading("Billing", level=1)
doc.add_paragraph("Refunds for unused seats within 30 days.")
section = doc.sections[0]
section.header.paragraphs[0].text = "Acme Internal — Confidential"
doc.save(ROOT / "handbook.docx")
rep = Document()
rep.add_heading("Q3 Data Pipeline Report", level=1)
rep.add_paragraph("Parsing coverage across PDF, HTML, Office and email.")
rep.save(ROOT / "report.docx")
# --- Excel: 'Q3 Pricing' visible + 'Archive' hidden; Annual is a real
# formula, so data_only=True returns None — the 6.3 gotcha, on purpose ---
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.title = "Q3 Pricing"
ws.append(["Plan", "Seats", "Monthly", "Annual"])
for plan, seats, monthly in [("Pro", 10, 20), ("Team", 50, 80),
("Enterprise", 200, 200)]:
r = ws.max_row + 1
ws.append([plan, seats, monthly, f"=C{r}*12"])
ws.merge_cells("A6:D6")
ws["A6"] = "Prices in USD, billed annually"
arch = wb.create_sheet("Archive")
arch.sheet_state = "hidden"
arch.append(["Plan", "Seats", "Monthly", "Annual"])
arch.append(["Legacy", 5, 10, 120])
wb.save(ROOT / "pricing.xlsx")
# --- PowerPoint ---
from pptx import Presentation
from pptx.util import Inches
write_tiny_png(ROOT / "assets" / "logo.png")
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[0]) # title slide
slide.shapes.title.text = "Q3 Roadmap Review"
slide.placeholders[1].text = "Data platform: parsing, chunking, retrieval"
slide = prs.slides.add_slide(prs.slide_layouts[1]) # title + content
slide.shapes.title.text = "Parsing coverage"
slide.placeholders[1].text = "Formats and their parsers"
gf = slide.shapes.add_table(3, 2, Inches(1), Inches(2.4),
Inches(5), Inches(1.5))
tbl = gf.table
for r, row in enumerate([["Format", "Parser"],
["PDF", "Docling + pypdf"],
["HTML", "trafilatura"]]):
for c, val in enumerate(row):
tbl.cell(r, c).text = val
slide.shapes.add_picture(str(ROOT / "assets" / "logo.png"),
Inches(6.5), Inches(1))
slide.notes_slide.notes_text_frame.text = (
"Emphasise the parser-registry design; demo the failure gallery.")
prs.save(ROOT / "quarterly-review.pptx")
# --- Jupyter notebook ---
import nbformat
from nbformat.v4 import (new_notebook, new_markdown_cell, new_code_cell,
new_output)
nb = new_notebook()
nb.cells = [
new_markdown_cell("# Churn analysis\n\nExploring the Q3 ticket export."),
new_code_cell("import pandas as pd\n"
"churn = pd.read_csv('data/tickets.csv')\n"
"churn.head()",
execution_count=1,
outputs=[new_output(
"execute_result",
data={"text/plain":
" ticket_id churned\n"
"0 T-1042 True\n"
"1 T-1043 False",
"text/html": "<table><tr><td>ticket_id</td></tr></table>"},
execution_count=1)]),
]
nbformat.write(nb, ROOT / "analysis.ipynb")
# --- email: .eml is RFC 5322 text — the stdlib email package writes it fine.
# Matches the headers the 7.1 output block shows ---
from email.message import EmailMessage
msg = EmailMessage()
msg["From"] = "Priya Nair <priya@acme.com>"
msg["To"] = "Support <support@acme.com>"
msg["Subject"] = "Invoice €1,240.00 missing"
msg["Date"] = "Tue, 04 Nov 2026 09:14:22 +0000"
msg["Message-ID"] = "<CAF123@mail.acme.com>"
msg.set_content("Hi, the invoice for EUR 1,240.00 never arrived. "
"Can you resend?")
msg.add_alternative(
"<p>Hi, the invoice for <b>EUR 1,240.00</b> never arrived. "
"Can you resend?</p>", subtype="html")
(ROOT / "ticket.eml").write_bytes(msg.as_bytes())
# --- EPUB (ebooklib is AGPL — fine for learning; 7.3 shows the
# licence-clean zipfile alternative) ---
from ebooklib import epub
book = epub.EpubBook()
book.set_identifier("acme-handbook-2026")
book.set_title("Acme Product Handbook")
book.set_language("en")
chapters = []
for name, title, body in [
("intro", "Introduction",
"<h1>Introduction</h1><p>Welcome to the Acme handbook.</p>"),
("billing", "Billing",
"<h1>Billing</h1><p>Plans, invoices and refunds.</p>"),
("api", "API reference",
"<h1>API</h1><p>Endpoints and authentication.</p>"),
]:
ch = epub.EpubHtml(title=title, file_name=f"{name}.xhtml", lang="en")
ch.content = f"<html><body>{body}</body></html>"
book.add_item(ch)
chapters.append(ch)
book.toc = tuple(chapters)
book.spine = ["nav"] + chapters
book.add_item(epub.EpubNcx())
book.add_item(epub.EpubNav())
epub.write_epub(ROOT / "book.epub", book)
# --- structured data ---
events = [
{"ts": "2026-11-01T09:00:00Z", "type": "page_view", "url": "/refunds"},
{"ts": "2026-11-01T09:00:04Z", "type": "click", "url": "/refunds#form"},
{"ts": "2026-11-01T09:01:12Z", "type": "page_view", "url": "/billing"},
{"ts": "2026-11-01T09:02:40Z", "type": "search", "q": "invoice missing"},
]
(ROOT / "events.jsonl").write_text(
"\n".join(json.dumps(e) for e in events) + "\n", encoding="utf-8")
with open(ROOT / "tickets.csv", "w", newline="", encoding="utf-8") as f:
w = csv.writer(f)
w.writerow(["ticket_id", "customer", "tier", "amount", "date"])
w.writerow(["T-1042", "Acme GmbH", "gold", "1240.00", "2026-11-04"])
w.writerow(["T-1043", "Globex", "silver", "89.50", "2026-11-04"])
w.writerow(["T-1044", "Initech", "gold", "512.00", "2026-11-05"])
# --- legacy Office: convert the modern files when LibreOffice is installed;
# otherwise drop any old .doc/.xls/.ppt you have into data/ yourself ---
soffice = shutil.which("soffice")
if soffice:
for src, target in [("handbook.docx", "doc"), ("pricing.xlsx", "xls"),
("quarterly-review.pptx", "ppt")]:
subprocess.run([soffice, "--headless", "--convert-to", target,
"--outdir", str(ROOT), str(ROOT / src)],
check=False, capture_output=True)
for produced, legacy in [(ROOT / "handbook.doc", ROOT / "legacy.doc"),
(ROOT / "pricing.xls", ROOT / "legacy.xls"),
(ROOT / "quarterly-review.ppt",
ROOT / "legacy.ppt")]:
if produced.exists():
produced.rename(legacy)
else:
print("note: soffice not found — drop any legacy .doc/.xls/.ppt into "
"data/ yourself (6.5 only needs *a* legacy file to convert)")
# encrypted.docx can't be generated by these libraries — create it in
# Word/LibreOffice: File → Protect Document → Encrypt with password, and
# use the password "correct-horse" (the one 6.7 decrypts with).
print("sample data written under", ROOT)
for p in sorted(ROOT.rglob("*")):
if p.is_file():
print(" ", p)It writes data/handbook.docx, data/handbook.pdf, data/report.docx, data/report.pdf, data/pricing.xlsx (with a hidden Archive sheet and real formulas), data/quarterly-review.pptx, data/analysis.ipynb, data/ticket.eml, data/book.epub, data/events.jsonl, data/tickets.csv, data/legacy.doc/.xls/.ppt (when LibreOffice is installed), data/uploads/report (a PDF with no extension, for the magic-bytes probe) and data/assets/logo.png. Two files can't be generated: data/encrypted.docx (create it in Word/LibreOffice with password correct-horse) and data/legacy.* without LibreOffice — the script prints a note in that case. Every snippet below that names one of these files assumes it lives under data/; paths in the snippets are written relative to the project root.
No .env file is needed: nothing in this lesson calls a model or an external service. If you later send hard pages to a vision model, the keys and conventions live in 03.6.
What you must be able to do after this lesson#
- Parse HTML into clean text and Markdown
- Extract the main content and metadata of a web page
- Fetch pages politely with robots.txt and conditional requests
- Parse an Office file into text with structure
- Choose a parser for a given file type
Why this matters for an AI engineer#
Parsing is where the data pipeline meets reality. A retrieval system is only as good as the text it ingests, and the parser decides what that text is: whether a table survived as a table or became a run-on sentence of prices and product names, whether a help-centre article includes the cookie banner in every chunk, whether a contract clause is attached to the right section heading. These failures are silent — the pipeline "works", the chunks exist, the embeddings are fine — and they surface later as wrong answers that are very hard to trace back.
| You'll hear... | You'll understand it after... |
|---|---|
| "Just scrape the page and strip the tags." | Part 2: why get_text() loses tables and headings |
| "BeautifulSoup or lxml?" | 2.1 and 2.3 |
| "The article text is missing the table." | 2.4 and the failure gallery |
| "Send it through trafilatura." | 2.4: the cascade and its trade-offs |
| "We need the page as Markdown." | 2.5 |
| "Where's the publish date?" | 2.7 and htmldate |
| "The site blocked our crawler." | Part 3 and 3.7 |
| "robots.txt says we can't crawl it." | 3.3 — and why you should respect it |
| "This page needs JavaScript." | 3.6 |
| "Use the llms.txt instead of scraping." | Part 4 |
| "Convert the docx to text." | Part 6: python-docx vs Pandoc vs Docling |
| "The spreadsheet has merged cells." | 6.3 |
| "It's a .doc file from 2004." | 6.5 |
| "Just use MarkItDown for everything." | 6.6 |
| "The file is password-protected." | 6.7 |
| "Flatten this nested JSON." | 8.2 |
| "Parse the .msg file." | 7.2 — and the licence question |
| "Read the ipynb as text?" | 9.2 |
| "The zip file is suspicious." | 11.3 |
Part 1: HTML for AI engineers#
1.1 What HTML actually is#
HTML (HyperText Markup Language) is a tree of nested elements. An element is an opening tag, its content, and a closing tag: <p>Hello <b>world</b></p> is a paragraph element containing the text "Hello " and a bold element containing "world". Tags nest, so the whole document is a tree — the DOM (Document Object Model), the same tree a browser builds and lets JavaScript manipulate:
flowchart TD
html["<html>"] --> head["<head>: title, meta, links, scripts"]
html --> body["<body>"]
body --> nav["<nav>: menus, breadcrumbs"]
body --> main["<main> / <article>: the actual content"]
main --> h1["<h1> heading"]
main --> p["<p> paragraph"]
main --> table["<table>: rows and cells"]
main --> pre["<pre><code>: code block"]
body --> footer["<footer>: links, copyright, cookie banner"]Two consequences matter for ingestion:
- Structure is explicit. A heading is an
<h1>–<h6>element, a list is<ul>/<ol>with<li>children, a table is<table>with<tr>/<td>/<th>. A good parser keeps this structure; a bad one flattens it to text and loses it forever. - Most of a page is not content. Navigation bars, cookie banners, newsletter signups, related-article carousels, ads, footers and script payloads routinely make up 60–80% of a page's HTML. The parser's first job is usually removal, not extraction.
1.2 How browsers read HTML (and why your parser behaves like one)#
HTML is designed to be forgiving. A browser doesn't reject <p>one<p>two — it knows the second <p> implicitly closes the first. It tolerates unclosed tags, attributes without quotes, stray </div>s, text in weird places, and uppercase tags. The HTML5 parsing algorithm — the same algorithm every modern browser implements — defines exactly how to build the tree from messy input, including error recovery.
This matters twice:
- For you: parsers built on the HTML5 algorithm (lxml's HTML parser, html5lib, selectolax's Lexbor engine, and — through it — BeautifulSoup with
lxmlorhtml5lib) will produce the same tree a browser would, quirks included. Python's ownhtml.parseris not a tree builder: it's a streaming tokenizer that calls your callbacks as it reads, so you decide what to do with the events. - For debugging: when a parser's output looks wrong, the question "what would Chrome do with this HTML?" is usually the right mental model. Open the page source in a browser's dev tools and inspect the DOM — that's the tree your parser is approximating.
1.3 Malformed HTML, encodings and character references#
Real-world HTML is messy. The common cases and their fixes:
| Problem | Example | What happens | Fix |
|---|---|---|---|
| Unclosed tags | <p>text at EOF |
Parser auto-closes at end of document | Nothing — HTML5 algorithm handles it |
| Misnested tags | <b><i>text</b></i> |
Browser re-parents: <b><i>text</i></b> |
Same — the tree is what it is; don't fight it |
| Uppercase tags | <DIV CLASS="x"> |
Treated as lowercase in HTML | Nothing needed |
| Attributes without quotes | <a href=/foo> |
Valid HTML | Nothing needed |
| Stray closing tags | </div> with no opener |
Ignored or closes nearest match | Nothing needed |
| Encoding lies | Page says UTF-8 but is Latin-1 | Mojibake: é for é |
05.5 owns ftfy-style repair; at parse time respect <meta charset> and HTTP Content-Type |
| Character references | &, é, 😀 |
Must be decoded to &, é, 😀 |
Parsers with convert_charrefs=True (the default in Python 3) do this for you |
<script>/<style> content |
JS/CSS as text | get_text() happily includes it |
Remove these elements before extracting text — every serious extractor does |
| Comments | <!-- a note to self --> |
Visible to the DOM, usually noise | Remove soup.find_all(string=lambda s: isinstance(s, Comment)) |
1.4 CSS selectors and XPath: the vocabulary every parser shares#
Every parser in this lesson speaks two query languages for finding elements:
- CSS selectors — the same syntax as in
document.querySelectorin JavaScript:"article h2"(descendant),"div.post"(class),"#main"(id),"ul > li"(child),"a[href^='https']"(attribute prefix),"tr:nth-child(2)"(position). BeautifulSoup's.select()(through thesoupsievelibrary),lxml.cssselect(throughcssselect) and selectolax's.css()(through Lexbor's own selector engine) all implement them. - XPath — the older, more expressive XML query language:
"//div[@class='post']/p","//a[starts-with(@href, 'https')]".lxml's is the reference implementation and the most complete; BeautifulSoup has no XPath support of its own (its.select()is CSS-only, throughsoupsieve). Note the other exceptions: selectolax has no XPath engine at all (its documentation offers CSS selectors only) andhtml.parserbuilds no tree to query — XPath is an lxml story.
When to use which: CSS selectors are what you write 95% of the time — they're shorter and you already know them from the web. XPath wins for things CSS can't express cleanly: "the <td> that is the 3rd child of its row", "text content matching a pattern" (//p[contains(., 'refund')]), or walking up to an ancestor. BeautifulSoup's find_all is a third, BeautifulSoup-specific mini-language (find_all("p", class_="intro")) that's often the most readable for simple cases.
1.5 Try it: the simplest possible parser#
Python's standard library ships html.parser, a streaming parser that calls your methods as it encounters tags, attributes and text. No tree, no dependencies — you accumulate what you want. Here's a working text extractor that skips <script>/<style> and keeps block-level line breaks:
# s1_1_htmlparser.py — stdlib only, no installs needed
from html.parser import HTMLParser
HTML = """
<article>
<h1>Refund policy</h1>
<p>We refund <b>unused</b> seats within 30 days.</p>
<ul><li>Full refund before use</li><li>50% after first use</li></ul>
</article>
<script>track("pageview")</script>
"""
BLOCK_TAGS = {"p", "div", "li", "h1", "h2", "h3", "tr", "section", "article"}
class TextExtractor(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True) # decode & é etc. for us
self.parts = []
self.skip = 0
def handle_starttag(self, tag, attrs):
if tag in {"script", "style", "noscript"}:
self.skip += 1
elif tag in BLOCK_TAGS:
self.parts.append("\n")
def handle_endtag(self, tag):
if tag in {"script", "style", "noscript"} and self.skip:
self.skip -= 1
elif tag in BLOCK_TAGS:
self.parts.append("\n")
def handle_data(self, data):
if not self.skip:
self.parts.append(data)
parser = TextExtractor()
parser.feed(HTML)
parser.close()
text = "".join(parser.parts)
print("\n".join(line.strip() for line in text.splitlines() if line.strip()))Refund policy
We refund unused seats within 30 days.
Full refund before use
50% after first useRun it: python s1_1_htmlparser.py. This is genuinely useful for the simplest cases — RSS feed bodies, notification emails, small fragments — but notice what it doesn't give you: no headings, no list structure, no table cells, no links, no way to say "only inside <article>". Everything in Part 2 exists to fix those gaps.
Part 2: Parsing HTML#
2.1 The parsers compared#
| Parser | What it is | Speed | Tree? | CSS selectors | Best for |
|---|---|---|---|---|---|
html.parser (stdlib) |
Streaming tokenizer, callbacks | Fast | No (you build it) | No | Tiny jobs, zero dependencies, learning |
lxml |
C library (libxml2/libxslt) bindings | Very fast | Yes | Via cssselect |
XPath-heavy work, huge documents, XHTML |
html5lib |
Pure-Python HTML5 algorithm | Slowest | Yes | Via cssselect |
Maximum spec fidelity when speed doesn't matter |
BeautifulSoup4 |
Pythonic tree API | Medium | Yes | Yes (soupsieve) |
The default choice: readable, forgiving, huge docs |
selectolax |
Cython bindings to Lexbor (HTML5) | Fastest | Yes | Yes (built-in) | Web-scale: thousands of pages, speed-critical |
Versions and licences as of November 2026: beautifulsoup4 4.15.0 (MIT), lxml 6.1.3 (BSD-3-Clause), html5lib 1.1 (MIT, last release 2020 — stable but effectively unmaintained), selectolax 1.0.2 (MIT), soupsieve 4.0.1 (MIT). BeautifulSoup4 is itself just a tree API: you tell it which engine to use — "lxml", "html.parser" or "html5lib" — and it wraps that engine's tree.
The recommendation that covers 90% of cases: BeautifulSoup4 with the lxml engine (BeautifulSoup(html, "lxml")). It's fast enough for almost everything, the API is the most readable, and .select() gives you CSS selectors. Reach for selectolax when you're parsing at scale (benchmark claims of 5–30× over BeautifulSoup/lxml on text extraction are plausible for very large batches, but measure on your own corpus). Reach for lxml.html directly when you need XPath's full power or are already in an lxml pipeline. html5lib only when you need spec-exact parsing of pathological pages and can afford the speed.
2.2 BeautifulSoup4 in practice#
# s2_2_bs4.py — needs: beautifulsoup4 lxml
from bs4 import BeautifulSoup, Comment, NavigableString, Tag
PAGE = """
<html><head><title>Refunds — Acme Help</title>
<meta property="og:title" content="Acme Refund Policy"/>
<link rel="canonical" href="https://help.acme.com/refunds"/>
</head><body>
<nav><a href="/">Home</a><a href="/pricing">Pricing</a></nav>
<article id="article">
<h1>Refund policy</h1>
<p class="lead">We refund <b>unused</b> seats within 30 days.</p>
<table><tr><th>Plan</th><th>Refund</th></tr>
<tr><td>Starter</td><td>Full</td></tr></table>
<pre><code>curl -X POST /refunds</code></pre>
</article>
<div id="cookie-banner">We use cookies.</div>
<footer>© 2026 Acme</footer>
</body></html>
"""
# The same bytes an HTTP fetch of this page would return — 2.4, 2.6 and 2.7
# use PAGE_HTML for "the fetched page".
PAGE_HTML = PAGE
soup = BeautifulSoup(PAGE, "lxml")
# --- find things ---
print("title:", soup.title.string)
print("h1:", soup.find("h1").get_text(strip=True))
print("article text:", soup.select_one("article").get_text(" ", strip=True))
# --- CSS selectors ---
print("table rows:", [r.get_text(" | ", strip=True) for r in soup.select("table tr")])
print("code:", soup.select_one("pre code").get_text())
# --- metadata ---
print("og:title:", soup.find("meta", attrs={"property": "og:title"})["content"])
print("canonical:", soup.find("link", rel="canonical")["href"])
# --- remove junk before extracting ---
for junk in soup.select("nav, footer, #cookie-banner, script, style"):
junk.decompose() # remove element AND its contents from the tree
for c in soup.find_all(string=lambda s: isinstance(s, Comment)):
c.extract()
# --- what remains is the content ---
print("clean text:", soup.select_one("article").get_text("\n", strip=True))title: Refunds — Acme Help
h1: Refund policy
article text: Refund policy We refund unused seats within 30 days. Plan Refund Starter Full curl -X POST /refunds
table rows: ['Plan | Refund', 'Starter | Full']
code: curl -X POST /refunds
og:title: Acme Refund Policy
canonical: https://help.acme.com/refunds
clean text: Refund policy
We refund
unused
seats within 30 days.
Plan
Refund
Starter
Full
curl -X POST /refundsAPI notes that matter:
.get_text(separator, strip)walks descendants and concatenates their text —strip=Truetrims each piece. It preserves no structure: notice the output above splits the sentence at the inline<b>("We refund" / "unused" / "seats within 30 days." on separate lines) and puts every table cell on its own line. For faithful structure, walk elements explicitly (headings →#, list items →-, table cells →|) as in 2.6..decompose()removes a tag and everything inside it from the tree permanently;.extract()removes it but returns the detached element (useful if you want to keep the nav links elsewhere);.unwrap()removes only the tag, keeping children.soup.find_alland.selectreturnResultSet(a list);.find/.select_onereturn the first match orNone— always check forNone, pages are inconsistent.Tagobjects have.name,.attrs,.text,.string(text if the tag has exactly one child),.parent,.parents,.next_sibling,.previous_sibling,.next_element,.find_next(),.find_parent().NavigableStringis a text node;Commentis a subclass — filter it out or it lands in your text.
2.3 selectolax and lxml for speed#
When you're parsing tens of thousands of pages, BeautifulSoup's pure-Python object model is the bottleneck. selectolax wraps the Lexbor HTML5 engine in Cython and is typically the fastest option:
# s2_3_selectolax.py — needs: selectolax
from selectolax.lexbor import LexborHTMLParser
html = """
<h1 id="title" data-updated="20201101">Hi there</h1>
<div class="post">First post body.</div>
<div class="post">Second post body.</div>
"""
tree = LexborHTMLParser(html)
print(tree.css_first("h1#title").text()) # 'Hi there'
print(tree.css_first("h1#title").attributes) # {'id': 'title', 'data-updated': '20201101'}
print([n.text() for n in tree.css(".post")]) # ['First post body.', 'Second post body.']
# remove junk before text extraction
for tag in tree.css("script, style, nav"):
tag.decompose()
print(tree.body.text(separator="\n") if tree.body else "")Hi there
{'id': 'title', 'data-updated': '20201101'}
['First post body.', 'Second post body.']
Hi there
First post body.
Second post body.Notes: as of selectolax 1.x the Lexbor backend is the only backend (from selectolax.lexbor import LexborHTMLParser); the old Modest backend and parse_fragment() were removed in 1.0.0 (October 2026). For fragments, pass is_fragment=True. Node API: .css(), .css_first(), .text(deep, separator, strip), .attributes, .html, .tag, .iter(), .decompose() — no .xpath(): selectolax queries are CSS-only (checked against the 1.0.2 README and release notes, November 2026).
lxml.html is the other fast path — C-backed, XPath-complete:
# s2_3_lxml.py — needs: lxml
from lxml import html as lh
doc = lh.fromstring("<div class='post'><p>Hello <b>world</b></p></div>")
print(doc.xpath("string(.//p)")) # 'Hello world' (text of first <p>)
print([p.text_content() for p in doc.xpath(".//p")])
print(lh.tostring(doc, encoding="unicode", method="text")) # 'Hello world'lxml also ships lxml.html.clean (a whitelist HTML sanitizer built in since lxml 5.2 — the old standalone lxml_html_clean package is obsolete) and lxml.html.diff for comparing trees. For CSS in lxml you need the cssselect package (doc.cssselect() isn't part of lxml core) — another reason BeautifulSoup is the friendlier default.
2.4 Main-content extraction#
The hardest part of web parsing isn't finding elements — it's deciding which elements are the article. Three mature approaches, all verified as of November 2026:
trafilatura 2.3.1 (Apache-2.0) — the current best general-purpose extractor. It runs a cascade: its own rule-based extractor first, then Mozilla's Readability and jusText as fallbacks when the result looks too short. Actively maintained (2.3.1 released October 2026).
# s2_4_trafilatura.py — needs: trafilatura
from trafilatura import fetch_url, extract, bare_extraction
# fetch_url does a polite GET and returns the HTML (None on failure)
html = fetch_url("https://example.com/article")
if html:
# markdown keeps headings/lists/tables/links; add url= to resolve relative links
md = extract(html, output_format="markdown",
include_links=True, include_tables=True,
include_comments=False, url="https://example.com/article")
print(md[:400] if md else "extraction returned None")
# bare_extraction returns a Document object with metadata + structured body
doc = bare_extraction(html, url="https://example.com/article")
if doc:
print("title:", doc.title)
print("author:", doc.author)
print("date:", doc.date)
print("text length:", len(doc.text or ""))
# Useful extract() options (see trafilatura docs for the full list):
# extract(html, output_format="markdown", include_links=True,
# include_tables=True, fast=True, # skip fallback cascade (~2x faster)
# favor_precision=True, # less boilerplate, maybe less text
# favor_recall=True, # more text, maybe more noise
# target_language="de", # needs trafilatura[all]
# prune_xpath='//div[@class="ad"]', # drop elements pre-extraction
# record_id="doc-042", url="https://example.com/article")title: The Quiet Rise of Local-First Software
author: Jane Doe
date: 2026-09-14
text length: 18432Options that matter (all shown in the code above): the precision preset trades recall for cleaner output, the recall preset the reverse; fast=True skips the Readability/jusText fallbacks for ~2× speed; target_language="de" drops other-language results (needs trafilatura[all]); prune_xpath removes elements before extraction; record_id stamps provenance. is_probably_readerable(html) — ported from Mozilla's Readability.js — guesses whether a page even has extractable main text, useful for routing. It is not exported at top level: from trafilatura.readability_lxml import is_probably_readerable (verified against 2.3.1); it accepts an HTML string or a parsed lxml tree.
readability-lxml 0.9 (Apache-2.0) — a Python port of Mozilla's Readability.js (the algorithm Firefox Reader Mode uses; maintained by buriy, synced to current readability.js). Simpler than trafilatura — one shot, returns an HTML fragment of the article:
# s2_4_readability.py — needs: readability-lxml
from readability import Document
doc = Document(PAGE_HTML) # PAGE_HTML = the fetched page (see 2.2)
print(doc.title()) # 'Refunds — Acme Help'
article_html = doc.summary() # HTML fragment of just the article
# then feed article_html into BeautifulSoup for cleanup/markdownify<html><body><div id="readability-page-1"><div>
<h1>Refund policy</h1>
<p>We refund <b>unused</b> seats within 30 days.</p>
...Its output keeps some HTML structure but also carries Readability's own wrapper divs and classes — expect to clean it. There's no cascade, no metadata, no markdown output.
justext 3.0.2 (BSD-2-Clause) — the oldest approach: classify each block-level element as "good" (content) or "boilerplate" using stopword lists and link-density heuristics. Less accurate than the other two on modern pages but transparent and dependency-free:
# s2_4_justext.py — needs: justext
import justext
stoplist = justext.get_stoplist("English")
paragraphs = justext.justext(PAGE_HTML, stoplist) # PAGE_HTML = fetched page (2.2)
text = "\n\n".join(p.text for p in paragraphs if not p.is_boilerplate)
print(text[:300])Each paragraph also exposes .class_type: 'good', 'neargood', 'bad' or 'short' (verified against 3.0.2 — note neargood has no hyphen and short exists too).
When to write your own rules instead: documentation sites, help centres and wikis have predictable structure — the article lives in a known container (<article>, #content, .docs-content, main). A CSS selector beats a heuristic extractor every time: faster, more accurate, and it fails loudly (returns empty) rather than silently when the site changes — which is what you want for change detection in 05.9. Heuristic extractors earn their keep on unknown pages: news sites, blogs, forums.
Invisible elements are a special case of boilerplate. Pages routinely contain content that is in the DOM but not on screen: [hidden] attributes, style="display:none"/visibility:hidden, aria-hidden="true", <template> contents (inert until JS clones them), and <noscript> fallbacks (what no-JS browsers see — often a duplicate or an alternate message). get_text() and naive CSS selection happily include all of it. trafilatura handles this for you: its rule-based pass excludes display:none/hidden/aria-hidden elements via XPath rules, and its Readability fallback runs is_node_visible() (trafilatura.readability_lxml), which checks the style attribute for display:none, the hidden attribute, and aria-hidden="true". If you write your own selector-based extraction, remove them explicitly:
# s2_4_invisible.py — needs: beautifulsoup4 lxml
from bs4 import BeautifulSoup
soup = BeautifulSoup(PAGE_HTML, "lxml") # PAGE_HTML = fetched page (2.2)
for junk in soup.select("[hidden], [aria-hidden='true'], "
"template, noscript, "
"[style*='display:none'], [style*='display: none'], "
"[style*='visibility:hidden']"):
junk.decompose()
# caveat: this misses JS-toggled content and CSS-class-hidden elements
# (.d-none etc.) — visibility is ultimately a computed-style question a
# static parser can't fully answer; trafilatura's rules cover the common cases.2.5 HTML → Markdown#
For LLM ingestion, Markdown is the ideal intermediate format: it preserves headings, lists, tables, code and links in a form models read natively and tokenizers handle well (02.2 covers why Markdown is token-efficient). Three libraries:
| Library | Version (Nov 2026) | Licence | Notes |
|---|---|---|---|
markdownify |
1.2.3 | MIT | Most popular; rich options; handles tables via GFM extension syntax |
html2text |
2025.4.15 | GPL-3.0 | Mature; body-width wrapping; GPL licence — check your project's licence compatibility |
html-to-markdown |
3.22.0 | MIT | Newer alternative with table support |
# s2_5_markdown.py — needs: markdownify (or html2text)
from markdownify import markdownify as md
html = """
<h2>Getting started</h2>
<ol><li>Install the CLI</li><li>Run <code>acme init</code></li></ol>
<table><tr><th>Plan</th><th>Price</th></tr><tr><td>Pro</td><td>$20</td></tr></table>
<a href="https://acme.com/docs">Full docs</a>
"""
print(md(html, heading_style="ATX", bullets="-"))
# heading_style: ATX gives '#'-style headings (default is Setext underlines)
# bullets: which bullet chars to cycle through for nested lists
# script/style are dropped by DEFAULT (convert_script/convert_style return
# ''). The strip=/convert= options only choose which tags get *converted* —
# an unconverted tag's children still pass through as text, so
# strip=["script"] would actually LEAK the JS. To drop tags *and* their
# content, remove them from the tree first (decompose, as in 2.2), or use
# strip=["img"]-style options for void tags only.
print(md("<p>See <a href='https://x.com'>the docs</a> <img src='i.png' alt='pic'></p>",
strip=["img"])) # drops the image, keeps the link## Getting started
1. Install the CLI
2. Run `acme init`
| Plan | Price |
| --- | --- |
| Pro | $20 |
[Full docs](https://acme.com/docs)html2text equivalent:
# s2_5_html2text.py — needs: html2text (GPL-3.0!)
import html2text
h = html2text.HTML2Text()
h.body_width = 0 # don't hard-wrap lines — wrapping destroys paragraph detection downstream
h.ignore_links = False
h.ignore_images = False
print(h.handle(html))And trafilatura already emits Markdown: extract(html, output_format="markdown") — often the best single call for articles.
2.6 Preserving structure: headings, lists, tables, code, links#
Markdown conversion is lossy in predictable ways. When structure matters — which it almost always does for chunking (05.6) — emit it deliberately:
# s2_6_structure.py — needs: beautifulsoup4 lxml markdownify
from bs4 import BeautifulSoup, Tag
from markdownify import markdownify as md
soup = BeautifulSoup(PAGE_HTML, "lxml") # PAGE_HTML = fetched page (2.2)
article = soup.select_one("article") or soup.body
def html_to_structured_md(el) -> str:
"""Walk the tree and emit Markdown that keeps document structure."""
parts = []
for node in el.descendants:
if not isinstance(node, Tag) or node.name in {"script", "style"}:
continue
if node.name in {"h1","h2","h3","h4","h5","h6"}:
level = int(node.name[1])
parts.append("#" * level + " " + node.get_text(" ", strip=True))
elif node.name == "pre":
parts.append("~~~\n" + node.get_text() + "\n~~~")
elif node.name == "table":
parts.append(md(str(node))) # markdownify emits a GFM table
return "\n\n".join(p for p in parts if p)
print(html_to_structured_md(article))# Refund policy
| Plan | Refund |
| --- | --- |
| Starter | Full |
~~~
curl -X POST /refunds
~~~Rules of thumb:
- Headings: map
<h1>–<h6>to#–######before markdownifying, or trustmarkdownify'sheading_style="ATX". Never flatten a page toget_text()if it has headings — you lose the section boundaries chunking depends on. - Lists:
<ul>/<ol>→-/1.items;<li>containing nested lists needs indentation —markdownifyhandles this; hand-rolled converters usually get it wrong. - Tables: keep them as GFM pipe tables (
| a | b |) or HTML<table>(models understand both; pipe tables are more token-efficient). Never join cells with spaces — that's the classic "price attaches to the wrong product" failure. - Code:
<pre><code>→ fenced blocks with the language class (<code class="language-python">→ apython-tagged fence). Inline<code>→ backticks. Preserve newlines exactly. - Links:
[text](https://example.com/page)— but resolve relative URLs to absolute before storing (the page's<base href>and canonical URL matter). Store the source URL as provenance; a corpus of relative link targets like../other-pageis useless later. - Images: keep
when alt text exists; flag figures for the vision-model route (03.6) — 05.2 covers the same decision for PDFs.
2.7 Metadata extraction#
Pages carry metadata in four places: HTTP headers, <head> tags, embedded structured data (JSON-LD, microdata, OpenGraph), and the visible text (dates, authors). Extract all four:
# s2_7_metadata.py — needs: beautifulsoup4 extruct htmldate w3lib
from bs4 import BeautifulSoup
import extruct
from htmldate import find_date
from w3lib.url import canonicalize_url
soup = BeautifulSoup(PAGE_HTML, "lxml") # PAGE_HTML = fetched page (2.2)
# 0. document language — <html lang> drives language routing downstream
# (target_language in trafilatura, langdetect in 05.5) and is often the
# only reliable signal on pages without JSON-LD
print("lang:", soup.html.get("lang") if soup.html else None)
# 1. head tags
meta = {}
for tag in soup.find_all("meta"):
key = tag.get("property") or tag.get("name") or tag.get("http-equiv")
if key and tag.get("content"):
meta[key] = tag["content"]
print("description:", meta.get("description"))
print("og:type:", meta.get("og:type"))
# 2. structured data — one call returns every syntax extruct knows;
# EVERY value is a list (empty when that syntax is absent)
data = extruct.extract(str(soup), base_url="https://help.acme.com/refunds")
print("json-ld:", data.get("json-ld")) # list of schema.org objects
print("opengraph:", data.get("opengraph")) # list of {namespace, properties} dicts
print("microdata:", data.get("microdata"))
# 3. dates — htmldate reads <time>, meta tags, JSON-LD, canonical-URL
# patterns and visible text. Pass the HTML you already have plus url=
# for URL-pattern hints: a bare URL string makes htmldate *download*
# the page itself (a second fetch you don't need).
print("date:", find_date(PAGE_HTML,
url="https://help.acme.com/blog/2026/09/refunds"))
# 4. canonical URL — always prefer it over the fetched URL for dedup/provenance
canon = soup.find("link", rel="canonical")
url = canon["href"] if canon else "https://help.acme.com/refunds"
print("canonicalized:", canonicalize_url(url))lang: en
description: How Acme handles refunds for unused seats.
og:type: article
json-ld: [{'@context': 'https://schema.org', '@type': 'Article',
'headline': 'Refund policy', 'datePublished': '2026-09-14',
'author': {'@type': 'Person', 'name': 'Jane Doe'}}]
opengraph: [{'namespace': {'og': 'http://ogp.me/ns#'},
'properties': [('og:title', 'Acme Refund Policy'),
('og:type', 'article'),
('og:url', 'https://help.acme.com/refunds')]}]
date: 2026-09-14
canonicalized: https://help.acme.com/refundsNotes:
extruct.extract(html, base_url=...)returns a dict keyed by syntax —json-ld,microdata,microformat,opengraph,rdfa,dublincore— and every value is a list (empty when that syntax is absent; verified against 0.18.0). Sodata["opengraph"][0]is a dict like{'namespace': {'og': 'http://ogp.me/ns#'}, 'properties': [('og:title', '…'), …]}— index the list, then readpropertiesas(name, value)tuples. JSON-LD is the richest: schema.orgArticle,Product,FAQPage,BreadcrumbListobjects map directly onto metadata fields. Passbase_urlso relative URLs inside the data resolve.htmldate.find_date(the only export in 1.11.0 — there is noextract_date/extract_metadata) accepts an HTML string/bytes, a parsed lxml tree, or a URL — and a bare URL makes it download the page, so pass your already-fetched HTML plusurl=for URL-pattern hints instead. It checks<time datetime>, meta tags (article:published_time,date,DC.date), JSON-LD, canonical-URL patterns and visible text, returning the bestYYYY-MM-DDguess orNone. It's multilingual; passoriginal_date=Trueto prefer publication over modified dates — for both dates, call it twice with the flag flipped (verified against 1.11.0).w3lib.url.canonicalize_urlnormalizes a URL for deduplication — but less than the name suggests: it percent-encodes, sorts query params, strips fragments and resolves./..dot segments, while keeping the scheme, port, path case, trailing slash and all query params (includingutm_*). 05.5 uses it for dedup; here it feeds provenance. For tracker stripping usecourlan.clean_url/check_url(Part 3.5) — and forhttp↔https,www.↔bare and trailing-slash variants, only the site's own<link rel="canonical">is reliable.- OpenGraph is the
og:*/twitter:*meta set — cheap, ubiquitous, worth reading even when JSON-LD exists.
Part 3: Fetching the web properly#
Parsing assumes you have the bytes. Getting them is its own engineering problem: politeness, correctness under change, JavaScript, and legal limits.
3.1 httpx: the HTTP client#
httpx 0.28.1 (BSD-3-Clause) is the modern choice — sync and async in one API, HTTP/2, timeouts as first-class objects. requests still works but is sync-only.
# s3_1_httpx.py — needs: httpx
import httpx
with httpx.Client(
timeout=httpx.Timeout(15.0, connect=5.0),
follow_redirects=True,
headers={"User-Agent": "AcmeDocsBot/1.0 (+https://acme.com/bot; contact: ops@acme.com)"},
) as client:
resp = client.get("https://help.acme.com/refunds")
resp.raise_for_status() # 4xx/5xx -> exception
html = resp.text # already decoded via charset detection
print(resp.status_code, resp.headers.get("content-type"), len(html))
print(resp.headers.get("etag"), resp.headers.get("last-modified"))Async version (the shape used at scale; concurrency limits are 03.9's topic — link, don't re-teach):
# s3_1_httpx_async.py — needs: httpx
import asyncio
import httpx
async def fetch(client: httpx.AsyncClient, url: str) -> tuple[str, str]:
resp = await client.get(url)
resp.raise_for_status()
return url, resp.text
async def main():
urls = ["https://help.acme.com/a", "https://help.acme.com/b"]
async with httpx.AsyncClient(timeout=15.0, follow_redirects=True) as client:
results = await asyncio.gather(*(fetch(client, u) for u in urls))
for url, html in results:
print(url, len(html))
asyncio.run(main())Always set a real User-Agent that identifies your bot and a contact — it's etiquette and many sites' ToS require it. httpx decodes resp.text for you using the Content-Type charset, falling back to charset-normalizer — never decode resp.content yourself.
3.2 Conditional requests: fetch only what changed#
HTTP gives you two validators for free — this is the cheapest change-detection you'll ever implement, and 05.9 builds incremental ingestion on it:
ETag— an opaque version tag the server assigns the representation. Send it back asIf-None-Match; if unchanged the server replies304 Not Modifiedwith no body.Last-Modified— a timestamp. Send it back asIf-Modified-Since; same deal.
# s3_2_conditional.py — needs: httpx
import httpx, pathlib
CACHE = pathlib.Path(".etag_cache")
def fetch_conditional(client: httpx.Client, url: str) -> str | None:
headers = {}
if CACHE.exists():
etag = CACHE.read_text().strip()
if etag:
headers["If-None-Match"] = etag
resp = client.get(url, headers=headers)
if resp.status_code == 304:
return None # unchanged — reuse stored copy
resp.raise_for_status()
if etag := resp.headers.get("etag"):
CACHE.write_text(etag)
return resp.text# first fetch: 200, stores W/"abc123"
# second fetch: 304 -> returns None, no body transferred3.3 robots.txt and crawl etiquette#
robots.txt (RFC 9309) is a per-site file at /robots.txt saying which paths automated agents may fetch. It is not access control — it's a request — but ignoring it gets you IP-banned and, in some jurisdictions, is a ToS violation. Check it before crawling anything you don't own:
# s3_3_robots.py — stdlib parser + httpx fetch; protego for fuller parsing
import urllib.robotparser
import httpx
UA = "AcmeDocsBot/1.0"
ROBOTS_URL = "https://help.acme.com/robots.txt"
def load_robots(url: str) -> urllib.robotparser.RobotFileParser | None:
"""Fetch robots.txt ourselves (own User-Agent, a timeout) and apply the
RFC 9309 status rules. Returns None when the file is *unreachable*."""
rp = urllib.robotparser.RobotFileParser()
try:
resp = httpx.get(url, headers={"User-Agent": UA}, timeout=10.0,
follow_redirects=True)
except httpx.HTTPError:
return None # network failure = unreachable
if resp.status_code == 200:
rp.parse(resp.text.splitlines())
elif 400 <= resp.status_code < 500:
rp.allow_all = True # "unavailable": no restrictions published
else:
return None # 5xx = unreachable
return rp
rp = load_robots(ROBOTS_URL)
if rp is None:
# RFC 9309: if robots.txt is unreachable, assume complete disallow for now
print("robots.txt unreachable — do not crawl; retry later")
else:
if rp.can_fetch(UA, "https://help.acme.com/refunds"):
print("allowed")
else:
print("disallowed — skip or ask for permission")
print("crawl-delay:", rp.crawl_delay(UA)) # seconds the site asks between hits
print("sitemaps:", rp.site_maps()) # Sitemap: lines, if presentWhy not simply call rp.set_url(...) and rp.read()? The standard library's read() sends Python's default User-Agent, has no timeout, treats a 401/403 on robots.txt as "disallow everything" (RFC 9309 treats every 4xx as "unavailable", meaning no restrictions), and lets network errors escape. Worse, a RobotFileParser that was never successfully loaded answers can_fetch(...) with False for every URL, which is the right fail-closed behaviour for an unreachable file but surprising if you swallowed the exception and expected "allowed". Loading the file yourself makes each case explicit. (This was checked against the CPython urllib.robotparser source, Python 3.13, November 2026.)
protego 0.7.0 (BSD-3-Clause) is the fuller parser — longest-match rules, wildcards, Allow/Disallow precedence — use it when robotparser's simplifications matter. rp.mtime()/rp.modified() track when you last fetched robots.txt; re-check it periodically on long crawls.
robots.txt only covers URLs — it says nothing about what a page contains. For that there are page-level directives you only discover after fetching: <meta name="robots" content="..."> in the HTML <head> and the X-Robots-Tag HTTP response header (which also works on non-HTML responses like PDFs and images). The values overlap the search-engine vocabulary: noindex/index (may this page be indexed), nofollow/follow (may crawlers follow its links), noarchive, nosnippet, noimageindex, none (= noindex,nofollow), all, unavailable_after, plus bot-specific overrides like googlebot. For a private RAG corpus the semantics are yours to define, but the polite default is: treat noindex as "don't ingest this page" (or ingest but flag it), treat nofollow as "don't expand links from this page during the crawl", and record which directive you saw in the document's metadata — a page that asked not to be indexed probably isn't canonical corpus material anyway. X-Robots-Tag is easy to miss because it lives in headers, not markup; check resp.headers alongside the HTML.
Etiquette that keeps you unbanned: identify yourself honestly, respect Crawl-delay and rate-limit yourself well below it, fetch each host sequentially or with low concurrency, don't hammer endpoints that 429/403 you, and honour opt-outs. These aren't just manners — they're what separates a corpus you can legally and reliably refresh from one that dies after one run.
3.4 Rate limiting, retries and timeouts#
Three separate concerns, three separate tools:
- Timeouts — always set them (
httpx.Timeout(15.0, connect=5.0)); a hung connection must not hang your pipeline. - Retries — transient failures (408, 425, 429, 5xx, connection resets, read timeouts) deserve a bounded retry with exponential backoff and
Retry-Afterawareness; permanent failures (other 4xx like 404/403) must not be retried.httpxhas no built-in retry;tenacity9.1.4 does it cleanly (the same library 03.8 uses for API calls):
# s3_4_retry.py — needs: httpx tenacity
import httpx
from tenacity import (retry, stop_after_attempt, retry_if_exception,
wait_exponential)
TRANSIENT_STATUS = {408, 425, 429, 500, 502, 503, 504}
def is_transient(exc: BaseException) -> bool:
"""Retry timeouts/transport errors and transient HTTP statuses only —
a 404 or 403 will never succeed on retry, so it must not be retried."""
if isinstance(exc, (httpx.TimeoutException, httpx.TransportError)):
return True
return (isinstance(exc, httpx.HTTPStatusError)
and exc.response.status_code in TRANSIENT_STATUS)
def wait_with_retry_after(retry_state) -> float:
"""Honour the server's Retry-After on 429/503; exponential otherwise."""
exc = retry_state.outcome.exception() if retry_state.outcome else None
if isinstance(exc, httpx.HTTPStatusError):
ra = exc.response.headers.get("retry-after")
if ra and ra.strip().isdigit():
return min(float(ra), 60.0) # cap so a hostile header can't stall you
return wait_exponential(multiplier=1, min=1, max=30)(retry_state)
@retry(
stop=stop_after_attempt(4),
wait=wait_with_retry_after,
retry=retry_if_exception(is_transient),
reraise=True,
)
def fetch(client: httpx.Client, url: str) -> httpx.Response:
resp = client.get(url)
if resp.status_code in TRANSIENT_STATUS:
raise httpx.HTTPStatusError("transient", request=resp.request,
response=resp)
resp.raise_for_status() # 4xx/5xx not in TRANSIENT_STATUS -> immediate raise
return resp- Rate limiting — cap requests per host per second. A token bucket per domain (keyed by
urlparse(url).netloc) is the standard pattern;asyncio.Semaphorebounds total concurrency. Keep per-host politeness separate from global throughput — 10 req/s to one host is an attack; 10 req/s spread over 100 hosts is fine.
3.5 URL canonicalization and dedup of near-identical pages#
The same page arrives under many URLs: http/https, www./bare, trailing slash, ?utm_source=x, session IDs, #fragments, reordered query params. Canonicalize before dedup or you'll ingest the same article five times — but know exactly what each tool does and doesn't unify (all behaviour below verified against w3lib 2.5.0 and courlan 1.4.0):
# s3_5_canonical.py — needs: w3lib courlan
from w3lib.url import canonicalize_url
from courlan import check_url, clean_url
urls = [
"https://help.acme.com/refunds?b=2&utm_medium=email&a=1#comments",
"https://help.acme.com/refunds?sessionid=abc123",
"https://help.acme.com/a/../b/./c",
]
for u in urls:
print("in :", u)
print("w3 :", canonicalize_url(u))
print("cl :", clean_url(u))
print("ck :", check_url(u))in : https://help.acme.com/refunds?b=2&utm_medium=email&a=1#comments
w3 : https://help.acme.com/refunds?a=1&b=2&utm_medium=email
cl : https://help.acme.com/refunds?a=1&b=2#comments
ck : ('https://help.acme.com/refunds?a=1&b=2#comments', 'acme.com')
in : https://help.acme.com/refunds?sessionid=abc123
w3 : https://help.acme.com/refunds?sessionid=abc123
cl : https://help.acme.com/refunds
ck : ('https://help.acme.com/refunds', 'acme.com')
in : https://help.acme.com/a/../b/./c
w3 : https://help.acme.com/b/c
cl : https://help.acme.com/a/../b/./c
ck : ('https://help.acme.com/a/../b/./c', 'acme.com')Read the three columns carefully — they are not interchangeable:
w3lib.url.canonicalize_urlis a pure normaliser: percent-encoding, query-arg sorting, fragment stripping,./..resolution, host lowercasing. It keeps the scheme, port, path case, trailing slash and every query param —utm_mediumsurvives.courlan.clean_url(and the URL half ofcheck_url) additionally strips known tracking params — itsTRACKERS_RElist is derived from the AdGuard/ClearURLs/Firefox query-stripping rules and catchesutm_*,fbclid,gclid,sessionid-style params — plus default ports. It does not resolve dot segments, and keeps scheme/trailing-slash/fragments.courlan.check_url(url, strict=False, with_redirects=False, language=None, with_nav=False, trailing_slash=True)returns(cleaned_url, registered_domain)orNone— its real value is the filter: it rejects non-HTTP(S) schemes,localhost, junk extensions (.png,.zip…), malformed URLs and (instrictmode) spam/path patterns. Use it as a fetch gate, not just a dedup key. Note the domain is the registered domain (acme.com, via public-suffix rules), not the host.
The honest conclusion: none of these unify http↔https, www.↔bare, trailing-slash or path-case variants — those need either the site's own <link rel="canonical"> (prefer it whenever present, 2.7; the site knows its duplicates better than you do) or your own normalisation rules on top (force https, strip www., drop the trailing slash, then hash). A practical dedup key is canonicalize_url() then your rule-based rewrite then clean_url() for trackers — layered, each doing what it's verified to do. Templated near-duplicates (same article, different locale/date in URL) are a cleaning/dedup problem — 05.5 covers MinHash-style near-dup detection.
3.6 JavaScript-rendered pages#
A growing share of the web renders content client-side: React/SPA docs, some help centres, anything behind a "loading…" shell. Your httpx GET returns the empty shell. Options, cheapest first:
- Look for the data source. SPAs fetch JSON from an API — find it in the page's JS or network tab, hit the JSON endpoint directly. Often faster and cleaner than rendering.
- Look for a static/markdown version. Many docs sites serve
.md,/llms.txt, or an API (see Part 4). 05.1 covers this preference order. Playwright— a real browser you drive from Python.playwright1.64.1 (Apache-2.0);playwright install chromiumdownloads the browser (~150 MB):
# s3_6_playwright.py — needs: playwright (+ `playwright install chromium`)
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page(
user_agent="AcmeDocsBot/1.0 (+https://acme.com/bot)",
)
page.goto("https://help.acme.com/dynamic-article", wait_until="networkidle")
html = page.content() # the rendered DOM, serialized
print(len(html))
browser.close()Cost: a real Chromium per page — orders of magnitude slower and heavier than httpx. Use it only where the content genuinely requires JS; route per-URL (static fetch first, escalate failures to Playwright) rather than rendering everything.
3.7 Anti-bot, legal and privacy#
Anti-bot reality: Cloudflare-style challenges, fingerprinting, IP reputation. Do not build evasion into your pipeline — it's a losing game and often unlawful. If a site blocks you, the correct response is backoff, respect, or an official data channel.
3.8 Hosted scraping and crawl APIs#
When you can't or shouldn't run your own crawler, hosted services exist: managed crawl/scrape APIs (return rendered HTML/markdown at scale), browser-as-a-service, SERP APIs, Common Crawl (free petabyte-scale web archive — commoncrawl.org, already in the glossary), and vertical APIs (news, e-commerce). Evaluate on: cost per page, JS rendering, geographic coverage, legal posture, data freshness, and whether you can get raw HTML vs pre-cleaned text. The category matters more than the brand for your architecture decision. The three names you will meet most often for LLM work (Crawl4AI, Firecrawl, Jina Reader) are compared, with the licence and privacy questions to ask, in 05.1, 3.4; 05.9's connector discussion returns to build-vs-buy.
3.9 Crawl scope and depth: frontier, same-domain, dedup-before-fetch#
If you do run your own crawler, three design decisions matter more than the fetch itself:
- Scope: same-domain vs cross-domain. A help-centre corpus is almost always same-domain (or same-site via subdomains) — restrict the frontier to the host (and declared sibling hosts) unless you have a reason to follow external links. Cross-domain crawling explodes the frontier, mixes licences and ToS regimes, and mostly harvests navigation chrome. Track "registrable domain" (what courlan's
check_urlreturns) rather than raw hostname soblog.acme.comandhelp.acme.comcan be treated as one site when you want them to be. - Depth: cap it. BFS depth is the difference between "the 400 help articles" and "every tag/archive/search page the site ever generated". Docs sites are usually shallow (≤3 clicks); forums and wikis are deep. Set
max_depthexplicitly — 2–3 for docs, more only when the corpus genuinely nests — and always cap total pages per run. Depth-first vs breadth-first matters less than the cap. - Dedup before fetch, not after. The frontier should hold canonicalised URLs (3.5): normalise on enqueue, skip URLs already seen or already fetched, and store the canonical key with the document. Fetching duplicates and deduping later wastes bandwidth and politely-hostile budget; deduping on enqueue is cheap because it's pure string work.
- Frontier sources beat link-following when available. A sitemap (4.1) or
llms.txt(4.2) enumerates exactly the pages the site wants indexed — deterministic, complete, ordered by the site's own structure. Link-following is the fallback for sites without either, and it's where depth/scope limits earn their keep.
A minimal frontier loop, for shape only (the full pipeline — rate limiting, retries, robots checks, storage — is 05.9's job):
# s3_9_frontier.py — stdlib only (shape sketch; wire in httpx + the
# politeness machinery from 3.2-3.4 before running for real)
from urllib.parse import urljoin, urlparse
from collections import deque
def crawl(start_url: str, fetch, extract_links,
max_depth: int = 3, max_pages: int = 500,
same_domain: bool = True) -> list[str]:
"""BFS over canonicalised URLs. `fetch(url) -> html` and
`extract_links(html, base_url) -> urls` are injected."""
seen, queue, out = set(), deque([(start_url, 0)]), []
host = urlparse(start_url).netloc
while queue and len(out) < max_pages:
url, depth = queue.popleft()
if url in seen:
continue
seen.add(url)
html = fetch(url)
out.append(url)
if depth >= max_depth:
continue
for link in extract_links(html, url):
absu = urljoin(url, link)
if same_domain and urlparse(absu).netloc != host:
continue
if absu not in seen:
queue.append((absu, depth + 1))
return outThe decision rule: sitemap/llms.txt enumeration first (complete, ordered, free), bounded BFS second (unknown sites), hosted crawl APIs third (JS-heavy or adversarial sites). Never crawl "everything" — every page you fetch is a politeness cost and a corpus-quality liability.
Part 4: Documentation and help-centre sources#
Deep-dive
Before scraping a docs site, check whether it offers a better channel — almost always it does.
4.1 Sitemaps#
sitemap.xml is the site's own list of every URL it wants indexed — the best URL inventory you'll get, free. Format: XML <urlset> with <url><loc>…</loc><lastmod>…</lastmod></url> entries (sitemaps.org protocol; <lastmod> is W3C datetime, <changefreq>/<priority> are hints crawlers mostly ignore). Index files (<sitemapindex>) point to child sitemaps when there are many.
# s4_1_sitemap.py — stdlib only (httpx only needed for the sitemapindex path)
import xml.etree.ElementTree as ET
import gzip
NS = "{http://www.sitemaps.org/schemas/sitemap/0.9}"
SITEMAP_XML = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url><loc>https://help.acme.com/getting-started</loc><lastmod>2026-10-01</lastmod></url>
<url><loc>https://help.acme.com/billing/refunds</loc><lastmod>2026-09-15</lastmod></url>
<url><loc>https://help.acme.com/billing/invoices</loc><lastmod>2026-09-15</lastmod></url>
</urlset>"""
def fetch(url: str) -> str:
import httpx
r = httpx.get(url, timeout=15, follow_redirects=True)
r.raise_for_status()
if url.endswith(".gz"):
return gzip.decompress(r.content).decode("utf-8")
return r.text
def urls_from_sitemap(xml_text: str):
root = ET.fromstring(xml_text)
if root.tag == f"{NS}sitemapindex":
for sm in root.findall(f"{NS}sitemap"):
yield from urls_from_sitemap(fetch(sm.find(f"{NS}loc").text))
return
for url in root.findall(f"{NS}url"):
loc = url.find(f"{NS}loc")
lastmod = url.find(f"{NS}lastmod")
yield loc.text, (lastmod.text if lastmod is not None else None)
# production call: urls_from_sitemap(fetch("https://help.acme.com/sitemap.xml"))
for loc, lastmod in urls_from_sitemap(SITEMAP_XML):
print(loc, lastmod)https://help.acme.com/getting-started 2026-10-01
https://help.acme.com/billing/refunds 2026-09-15
https://help.acme.com/billing/invoices 2026-09-15The <lastmod> is gold for incremental ingestion — it's the site's own freshness signal (05.9).
4.2 llms.txt and Markdown versions of pages#
llms.txt (community proposal by Jeremy Howard — the spec at llmstxt.org shows "v2", last modified August 10, 2026; check the site for the current revision) is a curated Markdown file at /llms.txt (or any subpath) that tells agents what's on the site: an H1 title, a blockquote summary, optional prose, then H2 "file lists" of [name](https://example.com/page.md) links to LLM-friendly content. The companion convention: pages offer a Markdown twin at the same URL with .md appended or replacing the extension (page.html.md or page.md), signalled by <link rel="alternate" type="text/markdown"> or an HTTP Link: header (rel="describedby" points to the covering llms.txt). The most specific llms.txt wins.
# s4_2_llmstxt.py — stdlib only
import re
LLMS_TXT = """# Acme Help Centre
> Official help documentation for Acme products.
## Guides
- [Getting started](https://help.acme.com/guides/start.md): onboarding path
- [Billing](https://help.acme.com/guides/billing.md): plans, invoices, refunds
## API reference
- [REST API](https://help.acme.com/api/rest.md): endpoints and auth
"""
title = re.search(r"^#\s+(.+)$", LLMS_TXT, re.M).group(1)
summary = re.search(r"^>\s*(.+)$", LLMS_TXT, re.M).group(1)
print(f"title: {title}\nsummary: {summary}")
for name, url, note in re.findall(r"- \[([^\]]+)\]\(([^)]+)\)(?::\s*(.*))?", LLMS_TXT):
print(f"link: {name} -> {url}" + (f" ({note.strip()})" if note else ""))title: Acme Help Centre
summary: Official help documentation for Acme products.
link: Getting started -> https://help.acme.com/guides/start.md (onboarding path)
link: Billing -> https://help.acme.com/guides/billing.md (plans, invoices, refunds)
link: REST API -> https://help.acme.com/api/rest.md (endpoints and auth)A second, newer way to get Markdown without a separate file is HTTP content negotiation: send Accept: text/markdown and a cooperating server (for example a site behind Cloudflare's Markdown for Agents feature, announced February 2026) answers the same URL with Content-Type: text/markdown. The sample s3_4b_markdown_negotiation.py and the caveats (HTML only, size limits, the Content-Signal header) are in 05.1, 3.4; treat it as one more thing to probe, never as something to rely on.
Adoption is real but uneven — thousands of sites publish it, docs platforms generate it, Chrome Lighthouse audits for it — but coverage is strongest for software documentation, weakest for marketing/content sites. Probe /llms.txt first; fall back to sitemap + HTML parsing.
4.3 Other better-than-scraping sources#
- The source repository. Most docs are generated from a repo (MkDocs, Docusaurus, Sphinx, GitBook). Clone it or use the GitHub API (
repos/{owner}/{repo}/contents) and read the raw Markdown/MDX/rST — cleanest possible input, full history, no boilerplate. - The docs platform's API. GitBook, ReadMe, Mintlify and similar expose content APIs; check
/docsfor an OpenAPI spec (openapi.json,/swagger.json) describing endpoints. /openapi.json/ Swagger / AsyncAPI for API reference — structured, authoritative, better than scraping the rendered reference.- RSS/Atom feeds for blogs and changelogs —
feedparser6.0.14 (BSD-2-Clause):feedparser.parse(url)returns entries with.title,.link,.published,.summary/.content. Don't know the feed URL? Autodiscover it: docs and blogs advertise feeds in<head>as<link rel="alternate" type="application/rss+xml" href="/feed.xml">(ortype="application/atom+xml", and the newer JSON Feed usesapplication/feed+json) — grep the page's<head>forrel="alternate"before guessing/rss.xmlor/feed. - Versioned docs. Docs sites version their content (
/v1/,/v2/,?version=). Record the version in metadata — a chunk from "v2 docs" retrieved for a "v1 product" question is a correctness bug (05.8).
Part 5: Markup formats#
Deep-dive
HTML isn't the only markup. Markdown, reStructuredText, AsciiDoc and LaTeX are authored markup — the source documents your corpus is often built from, and far cleaner than their rendered HTML.
5.1 Markdown#
Markdown is the lingua franca of docs, READMEs, wikis, chat and increasingly LLM I/O. Structure to preserve: ATX/Setext headings, fenced code blocks (language tag), lists (nested), tables (GFM), blockquotes, links/images, footnotes, admonitions (!!! note in MyST, > [!NOTE] in GitHub), front matter (YAML between ---), wiki links ([[Page]]).
# s5_1_markdown.py — needs: markdown-it-py python-frontmatter
import frontmatter
from markdown_it import MarkdownIt
TEXT = """---
title: Refund policy
author: Jane Doe
tags: [billing, refunds]
---
# Refunds
We refund **unused** seats within 30 days.
~~~python
# fenced code keeps its fence
refund_days = 30
~~~
| Plan | Refund |
| ---- | ------ |
| Pro | Full |
"""
post = frontmatter.loads(TEXT) # python-frontmatter
print("meta:", post.metadata["title"], post.metadata["tags"])
print("body starts:", post.content.splitlines()[0])
md = MarkdownIt("commonmark").enable("table")
tokens = md.parse(post.content)
for t in tokens:
if t.type in ("heading_open", "fence", "table_open", "bullet_list_open"):
print("block:", t.type, t.tag, t.map)meta: Refund policy ['billing', 'refunds']
body starts: # Refunds
block: heading_open h1 [4, 5]
block: fence code [8, 11]
block: table_open table [15, 19]Alternatives: mistune 3.4.0 (mistune.create_markdown() → callable renderer) and markdown 3.11.2 (markdown.markdown(text, extensions=[...]) → HTML, the opposite direction). markdown-it-py is the best token-stream API for walking structure; python-frontmatter 1.3.0 splits YAML front matter cleanly. For chunking, you mostly need the raw Markdown text plus its heading offsets — which token.map (line ranges) gives you.
5.2 reStructuredText, AsciiDoc and LaTeX#
- reStructuredText (rST) — Sphinx/Python docs, docutils 0.23 (triple-licensed: public domain, BSD and GPL — pick whichever suits your project):
from docutils.core import publish_doctreegives a traversable node tree (docutils.nodes); directives like.. note::,.. code-block:: pythonbecome nodes you can walk. Older but precise. - AsciiDoc — Antora/technical docs; no good pure-Python parser — use Pandoc.
- LaTeX — papers, theses; Pandoc reads it (
-f latex).
Pandoc (current 3.13, October 2026) is the universal converter — a Haskell binary, not a pip package (the pandoc/pypandoc PyPI packages are thin wrappers that fetch it):
# docx -> markdown (structure preserved: headings, tables, footnotes)
pandoc input.docx -t gfm-raw_html -o out.md
# html -> markdown
pandoc page.html -f html -t gfm -o page.md
# rst/asciidoc/latex/epub -> anything
pandoc doc.rst -t markdown -o doc.md
pandoc paper.tex -t markdown --wrap=none -o paper.md
# markdown -> docx/html/pdf/latex (the other direction too)
pandoc README.md -o README.docxPandoc is the right first call for any authored format conversion — its readers are more faithful than most Python libs because it's a real document processor, not a regex. Reach for it via subprocess or pypandoc 1.17.
Part 6: Office files#
6.1 OOXML: a zip of XML#
.docx, .xlsx and .pptx are all OOXML (Office Open XML): a ZIP archive of XML parts — word/document.xml, xl/workbook.xml, ppt/slides/slide1.xml — plus media, styles and relationships. Consequences:
- They're just zips:
zipfilecan list and extract them; the "real" content is XML inside. - Structure is explicit: headings are
<w:pStyle w:val="Heading1">, tables are<w:tbl>, slides are separate XML files — richer than flattened text. - Parsing untrusted OOXML means parsing untrusted XML: see 11.3 for defusedxml and entity attacks.
- Legacy
.doc/.xls/.pptare not zips — they're OLE2 compound binaries (different format entirely, hence LibreOffice conversion in 6.5).
6.2 Word (.docx): python-docx, mammoth, docx2txt#
python-docx 1.2.0 (MIT) is the standard reader/writer:
# s6_2_docx.py — needs: python-docx
from docx import Document
doc = Document("data/handbook.docx") # from make_sample_data.py
# core metadata
cp = doc.core_properties
print(cp.title, cp.author, cp.created, cp.modified)
# paragraphs in order — para.style.name gives 'Heading 1', 'List Bullet', 'Normal'...
for para in doc.paragraphs:
style = para.style.name if para.style else ""
if style.startswith("Heading"):
print(f"\n{'#' * int(style.split()[-1])} {para.text}")
elif para.text.strip():
print(para.text)
# tables — cell.text concatenates paragraphs; merged cells repeat content
for table in doc.tables:
for row in table.rows:
print(" | ".join(cell.text.strip().replace("\n", " ") for cell in row.cells))
# headers/footers live on sections, not the body
for section in doc.sections:
for p in section.header.paragraphs:
if p.text.strip():
print("[header]", p.text)
# images are inline_shapes (alt text is limited; see failure gallery)
print("images:", len(doc.inline_shapes))Acme Product Handbook Jane Doe 2013-12-23 23:15:00 2013-12-23 23:15:00
# Getting started
Install the CLI and run `acme init`.
# Billing
Refunds for unused seats within 30 days.
Plan | Seats | Price
Pro | 10 | $200
[header] Acme Internal — Confidential
images: 0API notes: a document built from scratch by python-docx inherits the dates of the library's built-in template (the template's own timestamp, 2013-12-23 23:15 UTC in python-docx 1.2.0, as in the first line above), not the day you ran the script, so treat created/modified from generated files as unreliable. doc.paragraphs covers body paragraphs only — text inside tables, headers, footers and text boxes is not in it; doc.tables covers body tables. para.runs splits text by formatting (a spell-check squiggle can split "refund" into runs) — use para.text for content. cell.merge/grid spans repeat merged text in row.cells, so dedupe when a cell spans columns. One fragility: style.startswith("Heading") + int(style.split()[-1]) assumes built-in style names like Heading 1–Heading 9 — custom styles (Heading 1 Char) or localised names (Überschrift 1) break the int() parse. For robustness match style.style_id (built-ins are Heading1…Heading9, no space) or keep an explicit name→level map.
The honest limits (check before relying on it): python-docx does not expose tracked changes (w:ins/w:del — revisions render as raw XML you must walk via doc.element), footnotes/endnotes, comments are partially supported in 1.2.0 (doc.comments/paragraph.add_comment per the 1.2.0 docs), fields (PAGE, REF), or text-box content. For a faithful "everything the document says" extraction — revisions, footnotes, fields resolved — use Pandoc or Docling (6.6).
Two simpler alternatives: mammoth 1.13.0 (BSD-2-Clause, a Python port of mammoth.js) — mammoth.convert_to_html(path) / convert_to_markdown(path) gives clean semantic HTML/Markdown fast, but drops headers/footers, footnotes and most structure; good for "give me the prose". docx2txt 0.9 — dead simple docx2txt.process(path) → plain text, unmaintained since 2025, no structure — a fallback only.
6.3 Excel (.xlsx): openpyxl and pandas#
A spreadsheet is structured data that happens to live in a file — decide early whether you want it as a table (rows → records) or as a document (sheets → prose). Almost always: table.
# s6_3_xlsx.py — needs: openpyxl pandas
from openpyxl import load_workbook
import pandas as pd
path = "data/pricing.xlsx" # from make_sample_data.py
# --- openpyxl: structure-aware ---
wb = load_workbook(path, read_only=True, data_only=True) # data_only -> cached formula RESULTS
print("sheets:", wb.sheetnames)
for ws in wb.worksheets:
print(f"[{ws.title}] state={ws.sheet_state} dims={ws.calculate_dimension()}")
for i, row in enumerate(ws.iter_rows(values_only=True)):
print(row)
if i >= 4:
break
wb.close()
# --- pandas: rows -> DataFrame (the usual ingestion shape) ---
xl = pd.read_excel(path, sheet_name=None) # dict[sheet_name -> DataFrame]
for name, df in xl.items():
print(name, df.shape)
print(df.head(2).to_string())sheets: ['Q3 Pricing', 'Archive']
[Q3 Pricing] state=visible dims=A1:D6
('Plan', 'Seats', 'Monthly', 'Annual')
('Pro', 10, 20, None)
('Team', 50, 80, None)
('Enterprise', 200, 200, None)
(None, None, None, None)
[Archive] state=hidden dims=A1:D2
('Plan', 'Seats', 'Monthly', 'Annual')
('Legacy', 5, 10, 120)
Q3 Pricing (5, 4)
Plan Seats Monthly Annual
0 Pro 10.0 20.0 NaN
1 Team 50.0 80.0 NaN
Archive (1, 4)
Plan Seats Monthly Annual
0 Legacy 5 10 120The details that bite:
- Formulas vs values. A cell containing
=B2*C12reads as the formula string unless you open withdata_only=True— which returns the cached result (orNoneif the file was never opened in Excel). Thepricing.xlsxfrommake_sample_data.pyis exactly this case: openpyxl wrote theAnnualformulas, so no cached values exist anddata_only=TruereturnsNonefor every formula cell (theNaNin the pandas frame above) — a file created by a library almost never has cached results; only files last saved by Excel/LibreOffice do.data_only=False(default) gives formulas — pick deliberately and record which. - Hidden sheets.
ws.sheet_stateis'visible','hidden'or'veryHidden'. Hidden sheets often hold scratch data — skip them by default but log that you did. - Merged cells.
ws.merged_cells.rangeslistsCellRanges; only the top-left cell holds the value, the rest areNone— forward-fill headers manually when a title spans columns. - Named ranges
wb.defined_namesmark the "real" data region in messy sheets. - Types: openpyxl returns
datetime,Decimal? (numbers as int/float), strings; dates needisinstancecare. pandas coerces aggressively — checkdf.dtypes. .xls(legacy binary) — openpyxl can't read it; pandas routes toxlrd(install separately) or convert via LibreOffice (6.5).read_only=Truestreams rows (memory-safe for huge files) but losesmerged_cells/data_validations— open normally for structure work, read-only for bulk extraction.
Security note (verified): openpyxl's own docs warn it does not guard against quadratic-blowup/billion-laughs XML attacks — install defusedxml alongside when parsing untrusted files (11.3).
6.4 PowerPoint (.pptx): python-pptx#
python-pptx 1.0.2 (MIT) reads the slide XML. Slides are the unit — one slide ≈ one chunk candidate; speaker notes are often the real content.
# s6_4_pptx.py — needs: python-pptx
from pptx import Presentation
from pptx.enum.shapes import MSO_SHAPE_TYPE
prs = Presentation("data/quarterly-review.pptx") # from make_sample_data.py
for i, slide in enumerate(prs.slides, 1):
print(f"\n=== Slide {i} ===")
for shape in slide.shapes:
if shape.has_text_frame:
text = shape.text_frame.text.strip()
if text:
kind = "TITLE" if shape == slide.shapes.title else "text"
print(f"[{kind}] {text}")
if shape.has_table:
for row in shape.table.rows:
print(" | ".join(c.text.strip() for c in row.cells))
if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
print("[image]", shape.name)
# speaker notes — frequently the substantive content
if slide.has_notes_slide:
notes = slide.notes_slide.notes_text_frame.text.strip()
if notes:
print("[notes]", notes)=== Slide 1 ===
[TITLE] Q3 Roadmap Review
[text] Data platform: parsing, chunking, retrieval
=== Slide 2 ===
[TITLE] Parsing coverage
[text] Formats and their parsers
Format | Parser
PDF | Docling + pypdf
HTML | trafilatura
[image] Picture 4
[notes] Emphasise the parser-registry design; demo the failure gallery.Notes: iterate slide.shapes in z-order (roughly reading order; shape.shape_id/top/left give position — sort by (top, left) when layout matters). Grouped shapes nest (shape.shapes on a group). Charts are GraphicFrame — extract underlying data via the chart part or fall back to a rendered description; tables via shape.table. prs.core_properties has title/author/dates. Reading order is a known weakness — pptx has no semantic order, only z-order and position.
6.5 Legacy binary .doc/.xls/.ppt, ODF and RTF#
Pre-2007 Office files are OLE2 compound binaries — no Python library parses them well. LibreOffice headless is the standard bridge (current stable 26.x, e.g. 26.8, as of November 2026):
# convert legacy -> modern, then parse with the tools above
soffice --headless --convert-to docx --outdir converted/ legacy.doc
soffice --headless --convert-to xlsx --outdir converted/ legacy.xls
soffice --headless --convert-to pptx --outdir converted/ legacy.ppt
soffice --headless --convert-to pdf --outdir converted/ anything.docx # or straight to PDF -> 05.2soffice runs without a display (--headless); batch-convert a directory in a loop. Alternative converters in the same class: Pandoc (reads .docx but not legacy .doc), MarkItDown (same OOXML-only scope), Apache Tika (tika 3.3.2, needs a Java runtime — the heavyweight fallback that reads almost anything via Apache Tika's format zoo).
- ODF (
.odt/.ods/.odp, OpenDocument — LibreOffice native):odfpy1.4.1 is effectively unmaintained (last release 2020) and ships Apache/GPL/LGPL licence classifiers — justsoffice --convert-toor Pandoc instead. - RTF:
striprtf0.0.35 (BSD-3-Clause) —from striprtf.striprtf import rtf_to_text; rtf_to_text(rtf_string)→ plain text (no structure);rtfparse0.9.5 (MIT) for a tree. RTF is rare in corpora; treat as plain text.
6.6 Universal converters: Pandoc, MarkItDown, Docling, Unstructured, Tika#
Four "front doors" convert many formats to Markdown/text in one call. Verified as of November 2026:
| Tool | Version | Licence | Strengths | Watch out for |
|---|---|---|---|---|
| Pandoc | 3.13 | GPL-2+ | Most faithful authored-format conversion (docx/pptx/odt/epub/rst/asciidoc/latex/html ↔ anything); real document processor | External binary; Markdown output is good but not identical to input semantics; tables/images need flags |
| MarkItDown | 0.1.9 | MIT | Microsoft; one convert() for pdf/office/html/csv/json/xml/zip/epub/audio/YouTube; optional deps per format; plugins (OCR via LLM vision, Azure Doc Intelligence, Azure Content Understanding) |
Still 0.x — API moves; quality is "good enough for LLMs", not publication-grade; OCR/AI features are cloud-billed |
| Docling | 2.147.0 | MIT | IBM Research → LF AI & Data; best-in-class PDF/layout understanding; unified DoclingDocument model; exports Markdown/DocTags/JSON; OCR engines (Tesseract/RapidOCR/Surya); VLM pipelines; huge format list incl. ODF, EPUB, EML/MSG, ICS, audio/video, Apple formats, XBRL |
Heavy dependency tree; PDF is its superpower — for docx/pptx python-docx/python-pptx are lighter |
| Unstructured | 0.27.36 | Apache-2.0 | Element-typed output (Title, NarrativeText, Table…) with metadata; partition() auto-detects via libmagic; per-format partition_* funcs; OSS lib is positioned for prototyping — production pushes you to their paid API/Pipelines |
OSS explicitly "not designed for production" per its own docs; needs libmagic for auto-detect; <3.14 Python only |
Apache Tika (tika) |
3.3.2 | Apache-2.0 | Reads ~1000 formats via a Java server; the "last resort" parser | Requires Java + Tika server; heavyweight; output is plain-ish text |
# s6_6_markitdown.py — needs: markitdown (+ 'markitdown[all]' for all formats)
from markitdown import MarkItDown
md = MarkItDown(enable_plugins=False) # plugins off by default; enable for OCR/DocIntel
result = md.convert("data/report.docx") # or convert_local()/convert_stream()/convert_response()
print(result.markdown[:500])
print(result.text_content[:200])# s6_6_docling.py — needs: docling
from docling.document_converter import DocumentConverter
converter = DocumentConverter()
doc = converter.convert("data/handbook.pdf").document # or a .docx/.pptx/.html/...
print(doc.export_to_markdown()[:500])
# doc.export_to_dict() gives the full DoclingDocument JSON (elements, provenance, tables)# s6_6_unstructured.py — needs: unstructured (+ libmagic on the system)
from unstructured.partition.auto import partition
elements = partition(filename="data/report.pdf") # or file=..., url=..., content_type=...
for el in elements:
print(type(el).__name__, "|", el.text[:80])
# each element has .text and .metadata (page_number, filetype, ...)# s6_6_pandoc.py — Pandoc 3.13 as a subprocess
import subprocess, pathlib
def to_markdown(path: str) -> str:
out = subprocess.run(
["pandoc", path, "-t", "gfm", "--wrap=none"],
capture_output=True, text=True, check=True,
)
return out.stdoutChoosing: authored Office files → python-docx/python-pptx/openpyxl for structure, Pandoc for "just give me faithful Markdown", MarkItDown for a quick uniform pass, Docling when layout/tables/OCR matter. PDFs → 05.2 owns that; Docling/MarkItDown are its front doors here. The honest summary: no single converter wins everywhere — the parser registry in 11.2 exists precisely because you route by format.
6.7 Encrypted Office files#
Office files can be password-protected. msoffcrypto-tool 6.1.0 (MIT) decrypts ECMA-376 Agile/Standard (OOXML) and legacy RC4 CryptoAPI formats — with a password you already have:
# s6_7_msoffcrypto.py — needs: msoffcrypto-tool
import io
import msoffcrypto
from docx import Document # python-docx, as in 6.2
with open("data/encrypted.docx", "rb") as f: # create per the Setup note
office_file = msoffcrypto.OfficeFile(f)
office_file.load_key(password="correct-horse") # or private_key= / secret_key=
buf = io.BytesIO()
office_file.decrypt(buf, verify_integrity=True) # HMAC check on agile files
buf.seek(0)
doc = Document(buf) # hand the decrypted stream to python-docxCLI: msoffcrypto-tool encrypted.docx decrypted.docx -p Passw0rd; -t tests whether a file is encrypted. load_key(verify_password=True) checks the password before decrypting (Agile/Standard only). Never brute-force passwords — route encrypted files to quarantine with a "needs credentials" status (05.9's error model); a password-protected corpus is a policy problem, not a parsing one.
Part 7: Email and document formats#
Deep-dive
7.1 .eml files: the standard library is enough#
An .eml is a raw RFC 5322 message — Python's email package parses it completely, no dependencies:
# s7_1_eml.py — stdlib only
from email import policy
from email.parser import BytesParser
from email.utils import getaddresses, parsedate_to_datetime
with open("data/ticket.eml", "rb") as f: # from make_sample_data.py
msg = BytesParser(policy=policy.default).parse(f)
print("subject:", msg["subject"])
print("from:", msg["from"])
print("to:", [a for _, a in getaddresses(msg.get_all("to", []))])
print("date:", parsedate_to_datetime(msg["date"]).isoformat())
print("message-id:", msg["message-id"])
print("in-reply-to:", msg["in-reply-to"])
for part in msg.walk():
if part.get_content_maintype() == "multipart":
continue
print("part:", part.get_content_type(),
"| disposition:", part.get_content_disposition())
body = msg.get_body(preferencelist=("plain",))
print("plain body:", body.get_content().strip() if body else "")subject: Invoice €1,240.00 missing
from: Priya Nair <priya@acme.com>
to: ['support@acme.com']
date: 2026-11-04T09:14:22+00:00
message-id: <CAF123@mail.acme.com>
in-reply-to: None
part: text/plain | disposition: None
part: text/html | disposition: None
plain body: Hi, the invoice for EUR 1,240.00 never arrived. Can you resend?policy.default gives you EmailMessage objects with decoded headers (msg["subject"] returns a header object — str() it), get_body(preferencelist=...) picks the best body part, part.get_payload(decode=True) gives attachment bytes, part.get_filename()/get_content_disposition() handle attachments. email.utils.getaddresses parses address lists; parsedate_to_datetime normalises dates. For a friendlier object model, mail-parser 4.10.0 (Apache-2.0, production-grade, by SpamScope) exposes .subject, .from_, .to, .cc, .date, .attachments, .headers, .body, .text_plain, .text_html — verified against 4.10.0. Two traps: there is no .sender (it silently resolves to a literal Sender: header, usually absent — use .from_, which returns (display_name, email) tuples like .to/.cc do), and the body parts are .text_plain/.text_html lists, not .text/.html (those names fall through to header lookup and return '' — a silent empty, worse than an error). It also reads .msg files (converts via extract-msg, install mail-parser[outlook]).
7.2 MBOX mailboxes and .msg files#
- MBOX (a mailbox file, many messages concatenated): stdlib
mailbox.mbox(path)iteratesmboxmessages — each is anmboxMessageyou parse with the sameemailAPI.mailbox.Maildirhandles Maildir-format folders. .msg(Outlook's binary format):extract-msg0.58.1 (GPL — licence flag) —msg = extract_msg.Message(path)→.subject,.sender,.to,.body,.attachments,.date,.cc.msg_parser1.2.0 (BSD) is stale (2019).mail-parser[outlook]wraps extract-msg so one API covers.eml+.msg— the cleanest choice despite the GPL underneath (your code isn't contaminated; the dependency's licence governs distribution of the lib — still, flag it for legal review).- Threads: reconstruct via
In-Reply-To/Referencesheaders (email.utils+ a dict keyed onMessage-ID), not by subject matching — subjects lie, headers don't. Quoted-reply stripping (>prefixes, "On … wrote:") is a cleaning concern — 05.5.
7.3 EPUB ebooks#
EPUB is a ZIP of XHTML + content.opf manifest. ebooklib 0.21 (AGPLv3+ — licence flag) reads/writes it properly:
# s7_3_epub.py — needs: ebooklib
import ebooklib
from ebooklib import epub
book = epub.read_epub("data/book.epub") # from make_sample_data.py
for item in book.get_items_of_type(ebooklib.ITEM_DOCUMENT):
html = item.get_content().decode("utf-8")
# item.get_name() -> 'OEBPS/chapter1.xhtml' — use as provenance
# feed html through the Part-2 HTML pipeline (BeautifulSoup -> markdown)
# true reading order lives in the OPF spine: list of (idref, linear) tuples
print("spine order:", [book.get_item_with_id(i).get_name()
for i, _ in book.spine])Licence-clean alternative: treat EPUB as a zip (zipfile) and parse each XHTML with BeautifulSoup — ~20 lines, no AGPL. Or Pandoc (pandoc book.epub -t markdown).
7.4 Google Docs and Sheets via export#
Google Workspace files aren't files — they're cloud docs. Their export endpoints return exchange formats without the API:
https://docs.google.com/document/d/{id}/export?format=docx (or txt, pdf, html, odt, rtf)
https://docs.google.com/spreadsheets/d/{id}/export?format=csv&gid={sheet_id}
https://docs.google.com/presentation/d/{id}/export/pdfRequires the doc to be shared "anyone with link" or use OAuth with the Drive/Docs API (05.1 covers connector auth). This is the pattern for every SaaS "export" — SharePoint/OneDrive (/download), Confluence (/exportword), Notion (API blocks→markdown). Prefer these over screen-scraping the rendered page every time.
Part 8: Structured data#
Deep-dive
Not everything is prose. Tables, records and APIs arrive as CSV, JSON, XML, YAML and Parquet — parse them as data, then render to text deliberately.
8.1 CSV and TSV#
# s8_1_csv.py — stdlib only
import csv
with open("data/tickets.csv", newline="", encoding="utf-8-sig") as f: # utf-8-sig strips BOM
sample = f.read(8192)
f.seek(0)
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|")
print("dialect:", dialect.delimiter, dialect.quotechar)
for row in csv.DictReader(f, dialect=dialect):
print(row)Notes: utf-8-sig handles the BOM Excel adds; csv.Sniffer guesses delimiter/quote but fails on messy files — fall back to csv.reader with explicit delimiter. TSV = same with delimiter="\t". pandas.read_csv adds dtype inference, parse_dates, na_values — use it when the file is big or you want a DataFrame; stdlib csv when you want streaming rows.
8.2 JSON and JSONL#
JSONL = one JSON object per line (logs, API dumps, fine-tune data). Parse per line, tolerate bad lines:
# s8_2_json.py — stdlib only
import json
for i, line in enumerate(open("data/events.jsonl", encoding="utf-8")):
line = line.strip()
if not line:
continue
try:
rec = json.loads(line)
except json.JSONDecodeError as e:
print(f"line {i+1}: bad json ({e}) — quarantine")
continue
print(rec.get("type"), rec.get("ts"))Nested JSON → flat text. Records with nested objects/arrays don't embed well; flatten deterministically:
# s8_2_flatten.py — stdlib only
import json
def flatten(obj, prefix=""):
out = {}
if isinstance(obj, dict):
for k, v in obj.items():
out.update(flatten(v, f"{prefix}{k}."))
elif isinstance(obj, list):
for i, v in enumerate(obj):
out.update(flatten(v, f"{prefix}{i}."))
else:
out[prefix[:-1]] = obj
return out
ROW = {"id": "T-1042", "customer": {"name": "Acme GmbH", "tier": "gold"},
"lines": [{"sku": "W-11", "qty": 2, "price": 49.0},
{"sku": "C-04", "qty": 1, "price": 12.5}]}
for k, v in flatten(ROW).items():
print(f"{k} = {v}")id = T-1042
customer.name = Acme GmbH
customer.tier = gold
lines.0.sku = W-11
lines.0.qty = 2
lines.0.price = 49.0
lines.1.sku = C-04
lines.1.qty = 1
lines.1.price = 12.5Index paths (lines.0.sku) are positional — fine for flat records; for deeply nested docs prefer entity-centric documents (one doc per customer, its orders as a table) over naive flattening — 05.1 covers structured→text strategies.
8.3 XML#
Sitemaps, RSS, OOXML internals, config files, JATS articles. xml.etree.ElementTree is stdlib; defusedxml 0.7.1 is the drop-in that blocks billion-laughs/entity-expansion attacks — use it for any XML you don't fully trust:
# s8_3_xml.py — needs: defusedxml
from defusedxml import ElementTree as ET # drop-in for xml.etree.ElementTree
root = ET.fromstring(xml_bytes)
for el in root.iter():
print(el.tag, el.attrib, (el.text or "").strip()[:50])Namespaces use Clark notation {uri}local — the {*}local wildcard (Python 3.8+) matches any namespace, handy for messy docs. For huge XML use ET.iterparse (streaming). RSS/Atom → feedparser (Part 4.3).
8.4 YAML#
pyyaml 6.0.3 (MIT): yaml.safe_load(text) → dict; yaml.safe_dump. Always safe_load, never load — load can execute arbitrary Python objects (a real RCE vector on untrusted YAML). YAML front matter, configs, OpenAPI specs, k8s manifests.
8.5 Parquet and columnar data#
Parquet (pyarrow 26.0.1, Apache-2.0; or pandas.read_parquet(engine="pyarrow")) is columnar — for analytics, not prose. Read it when the source is a table; convert rows to text via the same record→text templates as JSON/CSV. DuckDB can query Parquet/CSV/JSON in place — preview of the SQL path below.
8.6 SQL rows → text; spreadsheets as tables vs documents#
Two honest choices for tabular sources:
- Row-as-document / record-as-text — render each row (or entity group) to a sentence/paragraph template:
f"{row['name']} ({row['tier']} tier) paid {row['amount']} on {row['date']}."— good for retrieval over records; keep the template stable so chunks are uniform. - Text-to-SQL — leave data in the DB and let the model query it (Module 08A owns this); don't flatten what you can query.
Spreadsheets double as documents (a pricing sheet is a table; a project-plan sheet has narrative in cells) — extract the grid as a table for the table parts, and cell text as prose for narrative cells. Decide per sheet, record the choice.
Part 9: Code and notebooks#
Deep-dive
9.1 Code repositories#
A repo is a corpus of small, structured documents. What to extract and what to skip:
- File selection — respect
.gitignore(parse it withpathspecor a small matcher; don't ingestnode_modules,dist,.venv, binaries, lockfiles unless they're the subject). Detect language by extension and shebang/pyproject/package.jsonmarkers — extension lies (.hcould be C or C++ or Obj-C). - What to keep — source files as text (the code is the document);
README*,docs/,CHANGELOG, docstrings (AST-extractable). Skip minified/bundled/generated files (*.min.js,*.generated.*, vendored dirs). - Size limits — cap file size (a 5 MB generated file is noise); split huge files later (05.7 previews AST-aware code splitting).
9.2 Jupyter notebooks (.ipynb)#
.ipynb is JSON — cells have cell_type (markdown, code, raw) and source (list of strings or string); code cells also have outputs (streams, execute_result with text/plain or image data) and execution_count. nbformat 5.11.1 (BSD) is the reference reader:
# s9_2_ipynb.py — needs: nbformat
import nbformat
nb = nbformat.read("data/analysis.ipynb", as_version=4) # from make_sample_data.py
for cell in nb.cells:
src = "".join(cell.source) if isinstance(cell.source, list) else cell.source
if cell.cell_type == "markdown":
print("## md:", src.splitlines()[0][:60] if src.strip() else "(empty)")
elif cell.cell_type == "code":
print("## code:", src.splitlines()[0][:60] if src.strip() else "(empty)")
for out in cell.outputs:
if out.output_type == "stream":
print(" out:", "".join(out.text)[:60])
elif out.output_type == "execute_result" and "text/plain" in out.data:
print(" result:", "".join(out.data["text/plain"])[:60])## md: # Churn analysis
## code: import pandas as pd
result: ticket_id churned
0 T-1042 True
1 T-1043Decide deliberately: markdown cells → prose; code cells → code (with outputs as context); outputs can be huge — truncate or summarise (a 10,000-row execute_result is noise). Image outputs (image/png) route to the vision path or get dropped with a note. Provenance: notebook path + cell index.
Part 10: Transcripts and chat logs#
Deep-dive
10.1 Subtitles and meeting transcripts#
SRT/VTT (subtitle formats) and speaker-labelled transcripts share a shape: timed turns. Parse cues into (start, end, speaker, text) records — the timestamp is provenance, the speaker is metadata:
# s10_1_srt.py — stdlib only
import re
SRT = """1
00:00:01,000 --> 00:00:04,500
Thanks for joining the roadmap review.
2
00:00:05,000 --> 00:00:09,250
<v Priya>Nadia, can you walk us through the parser changes?</v>
"""
cue = re.compile(r"(\d+)\s*\n(\S+)\s*-->\s*(\S+)\s*\n(.*?)(?=\n\s*\n|\Z)", re.S)
for num, start, end, text in cue.findall(SRT):
speaker = re.search(r"<v\s+([^>]+)>", text) # VTT speaker tag
clean = re.sub(r"<[^>]+>", "", text).strip().replace("\n", " ")
prefix = f"{speaker.group(1)}: " if speaker else ""
print(f"[{num}] {start} -> {end}: {prefix}{clean}")[1] 00:00:01,000 -> 00:00:04,500: Thanks for joining the roadmap review.
[2] 00:00:05,000 -> 00:00:09,250: Priya: Nadia, can you walk us through the parser changes?VTT differs only in the header (WEBVTT) and . millisecond separators; <v Speaker> tags carry speaker names — strip the tag, keep the name as a prefix (Priya: …). For ASR transcripts (Whisper-style) there's no timing markup — segment on speaker turns (SPEAKER_00:) and sentence boundaries; filler words ("um", "uh") are a cleaning decision — 05.7 previews transcript-aware chunking.
10.2 Slack, Teams and chat exports#
Chat exports arrive as JSON/JSONL (Slack's standard workspace export is one JSON file per channel containing an array of message objects with user, ts, thread_ts, text, reactions, files — plus a users.json for ID→name resolution) or HTML archives. Parse per-message into records: {channel, ts, user, thread_ts, text}. Reconstruct threads by thread_ts; strip Slack markup (<@U123>, <#C456|channel>, <https://x|label>); resolve user IDs via the export's users.json. Teams exports are similar (Message/Reply JSON or HTML). Keep timestamps — "when did this decision happen" is a real query. 05.7 covers thread-aware chunking.
Part 11: The parser layer#
Everything above produces text. Production needs the machinery that decides which parser runs on which file and survives bad input.
11.1 File-type detection by content, not extension#
Extensions lie (report.pdf containing HTML, data.csv that's actually JSON). Detect by magic bytes — the file's own signature:
# s11_1_detect.py — needs: filetype (pure-python magic bytes)
import filetype
kind = filetype.guess("data/uploads/report") # PDF bytes, no extension
if kind:
print(kind.extension, kind.mime) # 'pdf', 'application/pdf'
else:
print("unknown — fall back to extension + content sniff")filetype1.2.0 (MIT, pure Python, no deps, last release 2022 — stable):guess(path_or_bytes)→.extension/.mime. Covers the common types (PDF, OOXML zip-based via internal names, PNG/JPEG, gzip…).python-magic0.4.27 wraps libmagic (magic.from_file(path, mime=True)) — far broader type coverage but needs the systemlibmagiclibrary installed;unstructured.partition()uses it the same way.mimetypes.guess_type(path)(stdlib) maps extension→MIME — use as the fallback, never the primary.- OOXML subtypes: all three are zips — peek inside (
word/,xl/,ppt/directories) to tell docx/xlsx/pptx apart;filetypedoes this for you.
11.2 The parser registry#
A registry maps detected type → parser function, with per-type options, size limits and timeouts, and fallbacks:
# s11_2_registry.py — pure stdlib skeleton (fill parsers from Parts 2-10)
from dataclasses import dataclass, field
from typing import Callable
import mimetypes
import filetype
@dataclass
class ParseResult:
text: str
metadata: dict = field(default_factory=dict)
warnings: list = field(default_factory=list)
Parser = Callable[[str, bytes], ParseResult] # (path, bytes) -> ParseResult
def _unwired(name: str) -> Parser:
"""Placeholder until you wire in the real parser from its Part —
fails loudly (NotImplementedError) instead of NameError."""
def _parse(path: str, data: bytes) -> ParseResult:
raise NotImplementedError(f"wire {name} to the parser from its Part")
return _parse
REGISTRY: dict[str, Parser] = {
"text/html": _unwired("extract_html"), # Part 2
"application/pdf": _unwired("extract_pdf"), # 05.2
"application/vnd.openxmlformats-officedocument.wordprocessingml.document":
_unwired("extract_docx"), # Part 6
"text/csv": _unwired("csv_to_text"), # Part 8
"application/json": _unwired("json_to_text"), # Part 8
}
def parse_file(path: str, data: bytes) -> ParseResult:
mime, _ = mimetypes.guess_type(path)
# 1. content sniff overrides extension
kind = filetype.guess(data)
if kind and kind.mime in REGISTRY:
mime = kind.mime
parser = REGISTRY.get(mime)
if parser is None:
# 2. fallback chain: try converters, else raw text with a warning
return ParseResult(text=data.decode("utf-8", "replace"),
warnings=[f"no parser for {mime}; raw text fallback"])
return parser(path, data)Add per-entry max_bytes, timeout_s, and a fallback parser; the registry is also where versioned parser names go into provenance (05.8). Per-file try/except isolates failures — one corrupt file never kills the batch (05.9 formalises the error model).
11.3 Zip bombs and malicious-file hygiene#
OOXML files are zips; zips can lie about size. A tiny .docx can decompress to gigabytes (zip bomb). Guard before parsing:
# s11_3_zipcheck.py — stdlib only
import zipfile, io
def check_zip_safety(data: bytes, max_ratio: float = 100.0,
max_total: int = 500_000_000) -> list[str]:
"""Pre-parse guard: metadata-only checks first, decompression last.
Returns warnings; an empty list means safe to hand to the worker."""
warnings = []
with zipfile.ZipFile(io.BytesIO(data)) as zf:
total = 0
for info in zf.infolist():
# entry names are metadata too — reject traversal/absolute paths
# before anything is extracted (zip-slip)
parts = info.filename.replace("\\", "/").split("/")
if info.filename.startswith(("/", "\\")) or ".." in parts:
warnings.append(f"{info.filename}: unsafe path")
ratio = info.file_size / max(info.compress_size, 1)
total += info.file_size
if ratio > max_ratio:
warnings.append(f"{info.filename}: ratio {ratio:.0f}:1")
if total > max_total:
warnings.append(f"total uncompressed {total:,} exceeds limit")
if warnings:
return warnings # never decompress a suspicious archive
# size/path gates passed: a CRC check is now bounded by max_total.
# (On a real bomb the ratio/total checks above fire first, so we
# never reach this line.)
bad = zf.testzip()
if bad:
warnings.append(f"corrupt entry: {bad}")
return warningsBuild the demo archive and run the guard on it:
# demo_zip_bomb.py — continues s11_3_zipcheck.py (same imports)
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
zf.writestr("zeros.bin", b"\x00" * 200_000) # 200 KB of zeros
print(check_zip_safety(buf.getvalue()))['zeros.bin: ratio 948:1']The demo archive is 200 KB of zeros — it compresses to ~211 bytes, a ~948:1 ratio, so the guard rejects it from the central-directory metadata alone without decompressing a single byte. (A benign zip returns []; a ../evil.txt entry returns ['../evil.txt: unsafe path'].)
Rules: cap compressed and uncompressed size, cap compression ratio, reject absolute paths/.. traversal in entry names — all from infolist() metadata, no decompression — and only CRC-check (testzip()) archives that already passed the size gates. The big one stays: don't parse untrusted files in your main process. Run parsers in a sandboxed worker (separate process/container, no network, memory limits); a malicious docx can exploit a parser bug. If you keep extracted HTML (not just text — e.g. a Readability summary() fragment) for later rendering, sanitise it first with nh3 0.3.7 (MIT, the maintained successor to bleach): nh3.clean(html) strips <script>, on*= handlers and javascript: URLs while keeping formatting. This previews Module 12's untrusted-input model.
11.4 Mapping into ParsedDocument#
05.2 defines ParsedDocument — the module's canonical parsed representation (pages/blocks/tables/provenance). Every parser in this lesson feeds it the same way: extract → emit blocks (heading/paragraph/table/code/image) → attach provenance (source URI, format, parser name+version, fetch time, page/section where known). Parsers here extend it where the format demands — an HTML page has no "pages" but has a URL and heading path; a slide deck has slides not pages; a spreadsheet has sheets. Keep the block abstraction uniform so 05.6 chunks identically regardless of source.
11.5 Archives and containers#
Real corpora rarely arrive as loose files. They arrive as a .zip of scanned contracts, a .tar.gz database export, a .7z of mixed downloads, an email-attachment bundle. An archive is a container of mixed files, so ingestion is unpack-then-dispatch: extract each member under limits, then feed it back through the same parse_file registry as if it had been dropped in the watched folder — one bad member fails alone, exactly like one bad file.
Detect by magic bytes, not extension: PK\x03\x04 for the zip family — which unfortunately includes .docx/.xlsx/.pptx/.epub, so the classifier must recognise those packages before generic unpacking shreds them into XML parts — \x1f\x8b for gzip (a .tar.gz or a single .gz stream), and ustar at offset 257 for plain tar. zipfile, tarfile and gzip are all standard library; .7z/.rar need py7zr or libarchive if you adopt them (add to the office-extra group).
The safety rules are 11.3's zip-bomb rules applied one level up, plus archive-specific ones:
- Limits: cap member count and total uncompressed bytes (reuse the 500 MB ceiling), and — new here — nesting depth. An archive inside an archive inside an archive is almost always hostile or a bug;
MAX_DEPTH = 3is plenty for legitimate corpora. - Provenance: record each member's path inside the archive as
bundle.zip!contracts/ms-01.pdf. The!separator survivesmimetypes.guess_type(it only reads the suffix), so the registry still routes correctly while lineage keeps the real location. - Encrypted members: skip and report — never brute-force, the same policy as encrypted PDFs in 05.2. They surface in the run report for a human holding the password.
We never call extractall/extract: members come back as bytes (zf.read(info), tf.extractfile(m).read()), so there is no path-traversal write to guard against — the .. check stays anyway because the name travels into provenance and logs. Nested archives recurse through unpack with depth + 1; leaf members return to the caller for parse_file dispatch, and per-member warnings (unsafe paths, encrypted files) collect in a problems list:
# s11_5_unpack.py — stdlib only; continues the s11_3 hygiene rules.
import gzip
import io
import tarfile
import zipfile
MAX_MEMBERS = 10_000 # entries per archive
MAX_TOTAL_BYTES = 500_000_000 # uncompressed bytes — same ceiling as 11.3
MAX_DEPTH = 3 # archives inside archives: stop here
def _package_kind(data: bytes) -> str:
"""Classify by magic bytes. 'package' = OOXML/EPUB — technically zips,
but they belong to dedicated parsers, not generic unpacking."""
if data[:4] == b"PK\x03\x04":
try:
with zipfile.ZipFile(io.BytesIO(data)) as zf:
names = set(zf.namelist()) # central directory: cheap
except zipfile.BadZipFile:
return ""
if "[Content_Types].xml" in names or "mimetype" in names:
return "package"
return "zip"
if data[:2] == b"\x1f\x8b":
return "gzip"
if data[257:262] == b"ustar":
return "tar"
return ""
def _zip_members(data: bytes, problems: list):
with zipfile.ZipFile(io.BytesIO(data)) as zf:
infos = [i for i in zf.infolist() if not i.is_dir()]
if len(infos) > MAX_MEMBERS:
raise ValueError("too many archive members")
if sum(i.file_size for i in infos) > MAX_TOTAL_BYTES:
raise ValueError("uncompressed archive too large")
for info in infos:
name = info.filename.replace("\\", "/")
parts = name.split("/")
if name.startswith("/") or ".." in parts:
problems.append(f"{name}: unsafe path — skipped")
continue
if info.flag_bits & 0x1: # encrypted flag
problems.append(f"{name}: encrypted — skipped, needs a human")
continue
yield name, zf.read(info)
def _tar_members(data: bytes, problems: list):
with tarfile.open(fileobj=io.BytesIO(data), mode="r:*") as tf:
members = [m for m in tf.getmembers() if m.isfile()]
if len(members) > MAX_MEMBERS:
raise ValueError("too many archive members")
if sum(m.size for m in members) > MAX_TOTAL_BYTES:
raise ValueError("uncompressed archive too large")
for m in members:
name = m.name.replace("\\", "/")
parts = name.split("/")
if name.startswith("/") or ".." in parts:
problems.append(f"{name}: unsafe path — skipped")
continue
yield name, tf.extractfile(m).read()
def _gzip_members(data: bytes, problems: list):
""".tar.gz via tarfile; a bare .gz is a single-member stream."""
try:
members = list(_tar_members(data, problems))
except tarfile.TarError:
members = [("(stream)", gzip.decompress(data))]
yield from members
def unpack(data: bytes, prefix: str = "", depth: int = 0,
problems: list | None = None):
"""Yield (virtual_path, member_bytes) for every leaf member.
Archives recurse with depth+1; OOXML/EPUB 'packages' are leaves —
the registry routes them to their dedicated parsers. Always pass a
`problems` list in the pipeline: per-member warnings go there."""
problems = [] if problems is None else problems
kind = _package_kind(data)
if kind in ("", "package"):
return # not a generic archive
if depth >= MAX_DEPTH:
raise ValueError("archive nesting deeper than MAX_DEPTH")
if kind == "zip":
members = _zip_members(data, problems)
elif kind == "gzip":
members = _gzip_members(data, problems)
else:
members = _tar_members(data, problems)
for name, blob in members:
vpath = f"{prefix}!{name}" if prefix else name
if _package_kind(blob) in ("zip", "gzip", "tar"):
yield from unpack(blob, vpath, depth + 1, problems)
else:
yield vpath, blobCaller side — the dispatch loop that makes archives just another input to the pipeline:
# ingest_bundle.py — continues s11_5_unpack.py (same file or import unpack from it)
# Assumes: parse_file() from s11_2_registry.py with its _unwired placeholders
# replaced by real parsers; store() is your own persistence function (05.9);
# data/bundle.zip is any zip you have built (the sample data does not make one).
import logging
from pathlib import Path
log = logging.getLogger(__name__)
problems: list[str] = []
archive_bytes = Path("data/bundle.zip").read_bytes()
for vpath, blob in unpack(archive_bytes, prefix="bundle.zip",
problems=problems):
# vpath is already "bundle.zip!contracts/ms-01.pdf" — guess_type reads
# the suffix, so the registry routes it like a loose file
try:
result = parse_file(vpath, blob)
store(result, source_path=vpath)
print("member:", vpath)
except Exception as exc: # per-member isolation, as in 11.2
problems.append(f"{vpath}: parse failed — {exc}")
for p in problems:
log.warning("archive member skipped: %s", p)member: bundle.zip!contracts/ms-01.pdf
member: bundle.zip!contracts/ms-02.pdf
member: bundle.zip!nested.zip!notes.txt
member: bundle.zip!handbook.docx
archive member skipped: bundle.zip!vault/k1.pem: encrypted — skipped, needs a humanThe nested zip was recursed into once and only its leaf appears; handbook.docx stays one member because _package_kind recognises it as an OOXML package and the registry sends it to the docx parser instead of shredding it into XML parts. (The last line is the log.warning output, which goes to stderr.)
Part 12: Choosing a parser#
12.1 Decision table#
| Input | Reach for | Why | Fallback |
|---|---|---|---|
| HTML article/page | trafilatura → markdown | cascade, metadata, markdown out | BeautifulSoup + CSS selector for known sites; readability-lxml |
| HTML at scale (10k+ pages) | selectolax or lxml.html | speed | BeautifulSoup+lxml |
| Docs/help centre | sitemap → per-page selector, or .md/llms.txt, or Accept: text/markdown (05.1, 3.4) |
structure is known | trafilatura |
| Many JS-heavy sites, no capacity to run browsers | Self-hosted or hosted LLM-ready crawler (Crawl4AI, Firecrawl, Jina Reader), after the terms and privacy check | rendering + Markdown in one call | Playwright + trafilatura |
| Markdown/rST source | raw text + markdown-it-py/docutils for structure | already clean | Pandoc |
| .docx | python-docx (structure) or mammoth/Pandoc (markdown) | native OOXML | Docling/MarkItDown for full fidelity |
| .xlsx | openpyxl/pandas → table records | it IS a table | LibreOffice→csv |
| .pptx | python-pptx per slide + notes | slide=unit | Pandoc/Docling |
| .doc/.xls/.ppt (legacy) | LibreOffice headless → modern | only real path | Apache Tika |
| .odt/.ods/.odp | LibreOffice or Pandoc | odfpy unmaintained | — |
| .rtf | striprtf → text | simple | rtfparse |
| .eml | stdlib email / mail-parser | RFC-complete | — |
| .msg | mail-parser[outlook] or extract-msg (GPL) | only real parsers | — |
| MBOX/Maildir | stdlib mailbox | built-in | — |
| .epub | ebooklib (AGPL) or zipfile+BS4 | zip of XHTML | Pandoc |
| Google Docs/Sheets | export endpoints / API | native formats | — |
| CSV/TSV | stdlib csv / pandas | trivial | — |
| JSON/JSONL | stdlib json + flatten | trivial | — |
| XML | defusedxml ET | safe | — |
| YAML | pyyaml safe_load | trivial | — |
| Parquet | pyarrow/pandas | columnar | DuckDB |
| Code repo | file selection + raw text | code is text | tree-sitter (05.7) |
| .ipynb | nbformat | cell model | raw JSON |
| SRT/VTT/transcript | regex/parser → turns | timed records | — |
| Slack/Teams export | JSON parse → records | structured | — |
.zip/.tar/.gz bundle |
stdlib unpack with limits → per-member registry | container of mixed files | 11.5 |
| Unknown/mixed | filetype detect → registry → MarkItDown/Docling/Tika | front doors | raw text + warning |
12.2 Failure gallery#
| What goes wrong | Why | Fix |
|---|---|---|
| Table flattened to "Pro 10 $200 Team 50 $800" | get_text() joins cells |
emit pipe tables / keep <table> structure |
| Header/footer repeated in every chunk | boilerplate not removed | strip header/footer/repeated n-grams (05.5) |
| Cookie banner in extracted text | extractor kept it | remove nav/banner selectors or use trafilatura precision mode |
| Two-column PDF-style interleaving on web | CSS multi-column read linearly | usually fine on web (DOM order ≠ visual); check column-count layouts |
| Script/JSON-LD dumped as text | get_text() includes <script> |
decompose script/style/noscript first |
Mojibake é |
wrong encoding guess | trust httpx charset; never re-decode bytes |
| Relative links dead | stored /docs/x not absolute |
urljoin(base, href) on every link |
| Same page ingested 5× | utm/session/trailing-slash variants | canonicalize_url + rel=canonical |
| JS page extracts to "Loading…" | SPA shell, no content in HTML | find JSON API, .md version, or Playwright |
| docx loses footnotes/revisions | python-docx doesn't expose them | Pandoc/Docling for full fidelity |
xlsx formulas read as =B2*C2 |
data_only=False | data_only=True (but None if no cached value) |
| Hidden scratch sheet ingested | sheet_state ignored | filter sheet_state != 'visible' |
| pptx reading order wrong | z-order ≠ reading order | sort by top/left; check layout |
| .doc file "parses" to garbage | it's OLE2 binary not OOXML | LibreOffice convert first |
| Email shows HTML tags | picked text/html part | preferencelist=("plain",) or html→text |
| Thread shows quoted history ×3 | no reply stripping | strip > + "On … wrote:" (05.5) |
| JSON nested object embeds poorly | no flatten/entity strategy | flatten() or entity-centric docs |
YAML !!python/object executes |
yaml.load unsafe | always safe_load |
| XML billion-laughs hangs parser | entity expansion | defusedxml |
| Zip bomb OOMs the worker | uncompressed size unchecked | check_zip_safety + sandbox |
| ipynb 10k-row output as text | outputs unbounded | truncate/summarise outputs |
| .msg fails "not a zip" | OLE2 not OOXML | extract-msg/mail-parser |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Strip all the tags and you have the text." | get_text() loses headings, lists, tables, code and links — the structure chunking needs. Emit Markdown/structure deliberately (2.6). |
| "BeautifulSoup is the parser." | It's a tree API over an engine (lxml, html.parser, html5lib). The engine decides fidelity and speed. |
"html5lib is the most correct so use it." |
It's spec-faithful but the slowest and unmaintained since 2020; lxml's HTML parser handles the same algorithm in C. |
| "The extension tells you the type." | Files lie. Detect by magic bytes (filetype, python-magic); OOXML subtypes need zip inspection. |
"data_only=True always gives values." |
It gives cached results — None for files never opened in Excel. |
| "python-docx reads everything in a .docx." | No tracked changes, footnotes, fields or text boxes — use Pandoc/Docling for full fidelity. |
"html2text is the obvious HTML→MD lib." |
It's GPL-3.0 — licence-incompatible for many projects; markdownify (MIT) is the default. |
| "Send every page through Playwright to be safe." | A real browser per page is 100× the cost; find the JSON API or .md version first, escalate only what needs JS. |
| "robots.txt is advisory, ignore it." | It's a request with legal/ToS force; ignoring it gets you banned and can be unlawful. |
"yaml.load is fine." |
It executes arbitrary Python objects — safe_load always. |
| "A zip is a zip, it's safe." | Zips can be bombs (948:1 in the demo) or contain path traversal — check before parsing, sandbox untrusted files. |
| "MarkItDown/Docling replace the specific parsers." | They're front doors — great for coverage, but python-docx/openpyxl/python-pptx give you more control for their formats; route by format. |
| "Scraping is fine if the page is public." | Public ≠ free to bulk-ingest — ToS, copyright, GDPR apply; prefer APIs/exports. Not legal advice. |
Key takeaways#
- HTML is a tree (DOM); parsers rebuild it the way browsers do. BeautifulSoup4+lxml is the default; selectolax/lxml.html for scale; html.parser for zero-dep jobs.
- Most of a page is boilerplate. Remove
script/style/nav/footer/cookie banners before extracting; use trafilatura's cascade for unknown pages, your own CSS selectors for known sites. - Keep structure: headings→
#, lists→-/1., tables→pipe tables, code→fences, links→absolute URLs.get_text()alone loses all of it. - Metadata lives in
<head>, JSON-LD/microdata (extruct), OpenGraph, and dates (htmldate) — capture it all as provenance. - Fetch politely: real User-Agent, timeouts, bounded retries (tenacity), per-host rate limits,
robots.txt(robotparser/protego), ETag/Last-Modified for cheap change detection, canonical URLs for dedup. - Prefer better-than-scraping sources: sitemaps,
llms.txt,.mdpage versions (orAccept: text/markdownwhere a site supports it), source repos, OpenAPI specs, RSS, SaaS export endpoints. - Office files: python-docx/openpyxl/python-pptx for structure; Pandoc/MarkItDown/Docling/Unstructured as universal front doors; LibreOffice headless for legacy .doc/.xls/.ppt; msoffcrypto-tool for encrypted files you have the password for.
- Structured data stays structured until you render it: csv/json/yaml/defusedxml/parquet → records → deliberate text templates or entity-centric documents.
- The parser layer is production code: detect type by content (magic bytes), route through a registry with limits/timeouts/fallbacks, isolate failures per file, guard zips, unpack archives member-by-member under count/size/depth limits with
!-joined provenance, sandbox untrusted input, and feed everything intoParsedDocumentwith provenance.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| DOM | The tree structure a browser (and parser) builds from HTML tags |
| Boilerplate | Repeated non-content page furniture: nav, ads, footers, cookie banners |
| CSS selector / XPath | Query languages for finding elements in a parsed tree |
| BeautifulSoup / selectolax / lxml | HTML parser libraries (tree API / Cython Lexbor / C libxml2) |
| trafilatura / readability / justext | Main-content extractors (cascade / Mozilla algorithm / stopword classifier) |
| markdownify / html2text | HTML→Markdown converters (MIT / GPL) |
| extruct / JSON-LD / OpenGraph | Structured-metadata extraction (syntax / schema.org embed / og:* meta) |
| htmldate / w3lib / courlan | Date extraction / URL canonicalization / URL filtering libraries |
| ETag / Last-Modified / 304 | HTTP validators for conditional (unchanged) fetches |
| robots.txt / Crawl-delay | Per-site fetch rules (RFC 9309) and requested delay |
| llms.txt | Curated Markdown site index for LLM agents (community proposal, v2) |
| crawl frontier / scope / depth | The set of URLs a crawler will visit; bounded by domain and depth caps |
<meta name="robots"> / X-Robots-Tag |
Per-page crawl directives (noindex, nofollow, …) in markup and headers |
| feed autodiscovery | Finding a site's RSS/Atom/JSON feed via <link rel="alternate"> in <head> |
| invisible elements | DOM content hidden from view: [hidden], display:none, aria-hidden, <template>, <noscript> |
| OOXML | Office Open XML — docx/xlsx/pptx as ZIP-of-XML |
| python-docx / openpyxl / python-pptx | Native OOXML readers for Word/Excel/PowerPoint |
| Pandoc / MarkItDown / Docling / Unstructured / Tika | Universal document converters / front doors |
| msoffcrypto-tool | Decrypts password-protected Office files (with the password) |
| defusedxml | XML parser hardened against entity-expansion attacks |
| magic bytes / filetype / python-magic | Content-based file-type detection |
| zip bomb | Archive whose tiny compressed size hides huge uncompressed content |
| parser registry | Dispatch table mapping detected file type → parser + limits |
archive member / ! provenance |
A file inside a .zip/.tar/.gz; outer.zip!inner/path records where it really lived |
| nesting depth | Archives can contain archives — cap recursion (MAX_DEPTH) so self-referential zips terminate |
| ParsedDocument | The module's canonical parsed output (defined in 05.2) |
Exercises#
- Selectors (2.2): parse
PAGEins2_2_bs4.pyand extract every<a>insidearticlewith its absolute URL (useurllib.parse.urljoinwith the page URL). Which ones were relative? - Extractor comparison (2.4): run
trafilatura.extract,Document(html).summary()andjustext.justexton the same three pages (one article, one docs page, one forum thread). Which wins per type? Where does each fail? - Metadata (2.7): write
extract_meta(html, url)returning{title, canonical, description, jsonld, date}using BeautifulSoup + extruct + htmldate. Test on a page with and without JSON-LD. - Conditional fetch (3.2): extend
fetch_conditionalto store{etag, last_modified, body_path}per URL in a JSON manifest, and handleLast-Modifiedwhen no ETag exists. - llms.txt (4.2): write
parse_llms_txt(text) -> list[(section, name, url, note)]handling the spec's H1/blockquote/H2-list structure properly (not just regex over the whole file). - docx structure (6.2): extend
s6_2_docx.pyto emit Markdown (#for Heading styles,-for List Bullet, pipe tables) instead of prints — feed the output tomarkdownify-free chunking logic mentally: where would you split? - xlsx formulas (6.3): open
pricing.xlsxwithdata_only=False, find formula cells, thendata_only=True— which cells returnNoneand why? - Email thread (7.2): parse two
.emlfiles where the second hasIn-Reply-To/Referencespointing to the first'sMessage-ID; reconstruct the thread order. - Flatten vs entity (8.2): take the nested
ROWand instead offlatten(), render it as one prose sentence per order line with the customer as context. Which embeds better and why? - Registry (11.2): add
max_bytesand afallbackchain toREGISTRYso an oversized.docxroutes tomammothand an unknown type to raw text with a warning; writeparse_fileto enforce the limit before calling the parser. - Failure gallery (12.2): pick three rows and write a failing-then-passing test for each (e.g., assert tables survive as
|, assertscripttext never appears).
Hints and worked answers
soup.select("article a")thenurllib.parse.urljoin(page_url, a.get("href"))—urljoinresolves/path,../up,#fragand bare filenames against the base; the relative ones are exactly those whosehrefdoesn't start withhttps?://.- Expected shape: trafilatura usually wins on articles (best precision + Markdown + metadata); readability-lxml is close on clean articles but keeps more chrome; justext classifies text blocks well on text-heavy pages but returns no structure or metadata. On docs pages all three tend to keep sidebar/nav — that's the signal to switch to per-site CSS selectors. Score each on answer survival and boilerplate residue, not length.
extruct.extract(html, base_url=url, syntaxes=["json-ld"])returns{"json-ld": [...]}(empty list when absent);htmldate.find_datefor the date; canonical from<link rel="canonical">. Without JSON-LD yourjsonldkey should be[]/None, not a crash.- Manifest = one JSON file
{url: {"etag": ..., "last_modified": ..., "body_path": ...}}; store each 200 body underbody_path; sendIf-None-Matchwhen you have an ETag elseIf-Modified-Since; on 304 re-readbody_path, on 200 rewrite body and both validators. - Walk lines tracking state:
#→ site title (skip),>blockquote → summary (skip),##→ current section, and each list item is a markdown link of the form- [display name](https://target)optionally followed by: note— emit(section, name, url, note)for those. The trap is regexing the whole file — H2 boundaries are what makesectionmeaningful. - Map
paragraph.style.name:Heading N→'#'*N,List Bullet/List Number→-/1.,Title→#; emit pipe tables fromdoc.tables. Split before each Heading 1 and after each table — never mid-table. - With
data_only=FalsetheAnnualcells read as the formula strings=C2*12etc.; withdata_only=Truethey returnNonebecause openpyxl wrote no cached values (only Excel/LibreOffice-saved files have them). The mergedA6:D6title cell is not a formula — it still reads its text. email.parser.BytesParser(policy=policy.default).parsebytes(raw)gives a message whose.get("Message-ID"),.get("In-Reply-To")and.get_all("References")expose the threading headers; buildid → messageandparent_id → childmaps, and the thread root is the message no other message references.- Good answer shape: one self-contained sentence per order line carrying the customer — e.g. "Order T-1042 (Acme GmbH, gold): 2× W-11 @ $49.00 and 1× C-04 @ $12.50" — or one entity-centric doc per customer. Prose wins for embedding because the customer↔line association survives inside a single chunk;
flatten()'slines.0.skukeys scatter it. - Turn each
REGISTRYvalue into an entry{parser, max_bytes, fallback}; inparse_file, after mime detection checklen(data) > entry.max_bytesbefore calling the parser and route toentry.fallback(mammoth for.docx); unknown mime walks the fallback chain then raw text + warning. The limit check must precede the call — that's the whole point. - Example:
assert "| Plan |" in outon a table-bearing page fails underget_text()and passes once tables emit pipe syntax;assert "<script>" not in outandassert "cookie" not in out.lower()likewise pin the failure-gallery fixes.
Check yourself#
- Why do parsers produce the same tree a browser does, and which Python parser does not?HTML5 parsing algorithm — browsers and spec-compliant parsers (lxml, html5lib, Lexbor/selectolax) implement it.
html.parseris a streaming tokenizer, not a tree builder. - What's the difference between
.decompose(),.extract()and.unwrap()in BeautifulSoup?decompose()removes element+contents permanently;extract()removes it but returns the detached element;unwrap()removes only the tag, keeping children. - When is
selectolaxworth the extra dependency over BeautifulSoup?At scale — Cython/Lexbor is much faster on large batches; for one-off or moderate corpora BeautifulSoup's readability wins. - What does
trafilatura's cascade do thatreadability-lxmldoesn't?trafilatura cascades its own extractor → Readability → jusText fallbacks, plus metadata/markdown output and options; readability-lxml is a single Readability.js shot returning HTML. - Why must you remove
<script>/<style>beforeget_text()?Their text content would pollute your output — JS/CSS isn't page content. - What's the difference between
markdownifyandhtml2textbeyond API — and why does it matter?Licence: html2text is GPL-3.0, markdownify is MIT — matters for commercial/copyleft-incompatible projects. - Name four places page metadata hides and the tool that reads each.
<head>meta tags (BeautifulSoup), JSON-LD/microdata (extruct), OpenGraph (extruct/meta), dates (htmldate). - What cheap HTTP mechanisms reduce refetching and respect crawl rules — name the conditional-request validators, the robots.txt parsers, and the rate-limiting pattern?HTTP validators: send
If-None-Match/If-Modified-Since, get304+ no body when unchanged — free incremental-fetch signal.robots.txtis a crawl request (RFC 9309) — honour it or risk bans/ToS issues;urllib.robotparser(stdlib) andprotegoparse it. Rate limiting = a token bucket per host (urlparse(url).netloc) plusasyncio.Semaphorefor total concurrency. - When do you need Playwright, and what's the cheaper first check?Only when content requires client-side JS; first check for a JSON API endpoint or a
.md/llms.txt version. - What's the difference between
llms.txtandsitemap.xml, and which do you check first?llms.txt is a curated agent index with links to markdown; sitemap.xml is a full URL inventory for search engines — check llms.txt first for docs. - Why is
python-docxnot enough for a faithful .docx extraction?It doesn't expose tracked changes, footnotes/endnotes, fields, or text-box content — revisions/footnotes need raw XML or Pandoc/Docling. - What's the formula-vs-value gotcha in openpyxl, and when does
data_only=TruereturnNone?Cells store formulas as strings unlessdata_only=True, which returns cached results —Noneif the file was never opened in Excel (always true for library-generated files). - Which universal converter would you pick for a
.docfile from 2004, and why not Pandoc?LibreOffice headless (soffice --convert-to) — it's OLE2 binary, which Pandoc/MarkItDown/python-docx can't read. - Why is
yaml.loaddangerous and what's the fix?yaml.loadcan instantiate arbitrary Python objects (RCE); useyaml.safe_load. - What's a zip bomb and what checks guard against it?A compressed archive hiding huge uncompressed content; check compression ratio, total uncompressed size and entry names (
../absolute paths) frominfolist()metadata — before any decompression — CRC-check only archives that pass the gates, and sandbox untrusted parsing. - Why must generic archive unpacking leave a
.docxmember alone instead of recursing into it?Because a.docxis a zip of XML parts — recursing would shred it into[Content_Types].xml,word/document.xmletc. instead of producing document text. OOXML/EPUB are detected as "packages" (content check, not extension) and routed to their dedicated parsers as leaf members (11.5).
Further resources#
- BeautifulSoup4 docs — https://www.crummy.com/software/BeautifulSoup/bs4/doc/ (the
.select()/.find_all()reference) - selectolax — https://github.com/rushter/selectolax and https://selectolax.readthedocs.io
- trafilatura — https://trafilatura.readthedocs.io (extraction functions, precision/recall presets)
- python-readability (readability-lxml) — https://github.com/buriy/python-readability
- justext — https://github.com/miso-belica/jusText
- markdownify — https://github.com/matthewwithanm/python-markdownify
- extruct — https://github.com/scrapinghub/extruct
- htmldate / courlan / w3lib — https://github.com/adbar/htmldate, https://github.com/adbar/courlan, https://github.com/scrapy/w3lib
- RFC 9309 (robots.txt) — https://datatracker.ietf.org/doc/html/rfc9309
- Sitemaps protocol — https://www.sitemaps.org/protocol.html
- llms.txt spec (v2) — https://llmstxt.org
- python-docx — https://python-docx.readthedocs.io · openpyxl — https://openpyxl.readthedocs.io · python-pptx — https://python-pptx.readthedocs.io
- Pandoc — https://pandoc.org · MarkItDown — https://github.com/microsoft/markitdown · Docling — https://docling-project.github.io/docling · Unstructured OSS docs — https://docs.unstructured.io/open-source/introduction/overview
- msoffcrypto-tool — https://github.com/nolze/msoffcrypto-tool · mail-parser — https://github.com/SpamScope/mail-parser · ebooklib — https://github.com/aerkalov/ebooklib · defusedxml — https://github.com/tiran/defusedxml
- Playwright for Python — https://playwright.dev/python/docs/intro
← 05.2 — Parsing PDFs | Module 05 overview | 05.4 — OCR and Scanned Documents →