Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 20 min · revision 2

Parsing Documents, Scans and Tables into Clean Text

Turn an HTML page, a Markdown file and a PDF with a table and a scanned page into clean Markdown that keeps headings, lists, tables and code, and flag the pages that still need OCR or a vision-capable model.

Contentsand lesson path

What you will learn

  • Parse PDF, HTML and Markdown into clean text while preserving structure such as headings, tables and code blocks.

01. The problem

You are building the corpus for a question-answering assistant over the documentation of Larkspur, a small job scheduler. Larkspur is made up, so every file in this lesson is generated on your machine. Its documentation arrives in three shapes, as it often does in real projects:

  • an HTML page exported from the docs website, wrapped in navigation, a cookie banner, a script and a footer;
  • a Markdown source file with YAML front matter, an editor's HTML comment and a code sample;
  • a PDF operations sheet with a table of limits, plus a second page that is only a scanned image.

The chunkers in the rest of this skill need one clean text per document that keeps the structure a reader relies on: headings and their levels, lists, tables with their header row, and code with every space intact. Markdown is a good common target: plain text that models read well, with unambiguous markers for headings, tables and code.

The goal is a docs.jsonl file with one record per document: its source path, its text as Markdown, the character offset where each PDF page starts, and the pages that still need OCR.

02. Step 1: Set up and create the samples

Install three parsers: Beautiful Soup for HTML, markdown-it-py (a CommonMark parser) and PyMuPDF. Tested with Python 3.12, beautifulsoup4 4.15, markdown-it-py 4.3 and PyMuPDF 2.1. Since version 2.0, installing PyMuPDF also installs its pymupdf-layout and pymupdf4llm add-ons, with onnxruntime, so the download is larger than the name suggests. PyMuPDF 1.x, where the layout add-on is optional, prints a one-line tip about it the first time it analyses a layout; the export line turns that tip off (in PowerShell: $env:PYMUPDF_SUGGEST_LAYOUT_ANALYZER = "0").

Terminal
mkdir parse-docs && cd parse-docs
python3 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install beautifulsoup4 markdown-it-py pymupdf
export PYMUPDF_SUGGEST_LAYOUT_ANALYZER=0

The script writes the three samples into samples/. The PDF's second page is a picture of the first with no text behind it, exactly what a scanner without OCR produces.

Python · make_samples.py
"""Write three small sample documents into samples/."""
from pathlib import Path

import pymupdf

OUT = Path("samples")
OUT.mkdir(exist_ok=True)

HTML_PAGE = """<!doctype html>
<html><head><title>Configuration · Larkspur docs</title>
<script>window.analytics = [];</script></head>
<body>
<div class="cookie-banner">We use cookies. <button>Accept</button></div>
<nav><a href="/">Home</a> <a href="/install">Install</a> <a href="/api">API</a></nav>
<main>
<h1>Configuration</h1>
<p>Larkspur reads <code>larkspur.toml</code> from the working directory.</p>
<h2>Workers</h2>
<p>The <code>workers</code> setting controls how many jobs run at once.</p>
<ul><li>Default: 4</li><li>Each worker is a separate process</li></ul>
<h2>Example</h2>
<pre><code class="language-toml">workers = 8
timezone = "Europe/London"

[logging]
level = "debug"</code></pre>
<h2>Settings reference</h2>
<table>
<tr><th>Setting</th><th>Default</th><th>Environment variable</th></tr>
<tr><td>workers</td><td>4</td><td>LARKSPUR_WORKERS</td></tr>
<tr><td>timezone</td><td>UTC</td><td>LARKSPUR_TZ</td></tr>
</table>
</main>
<footer>© 2026 Larkspur contributors · <a href="/privacy">Privacy</a></footer>
</body></html>
"""

MARKDOWN_PAGE = """---
title: Retries and failures
sidebar_position: 4
---

# Retries and failures

<!-- TODO: add a diagram of the retry timeline -->

A job fails when it raises an exception or exits with a non-zero code.

## Retry policy

Failed jobs are retried up to 3 times. Turn retries off per job:

```python
# max_retries = 0 means: fail on the first error
@job(max_retries=0)
def nightly_report():
    ...
```

## Dead-letter queue

After the last retry the job moves to the dead-letter queue for 14 days.
"""

PDF_HTML = """
<h1>Larkspur operations sheet</h1>
<p>The limits operators ask about most. They apply per process.</p>
<h2>Limits</h2>
<p>Raise a limit only after checking memory use.</p>
<table style="border-collapse: collapse">
<tr><th>Limit</th><th>Default</th><th>Maximum</th></tr>
<tr><td>Workers</td><td>4</td><td>64</td></tr>
<tr><td>Retries</td><td>3</td><td>10</td></tr>
<tr><td>Timeout (minutes)</td><td>15</td><td>720</td></tr>
</table>
"""
CSS = "th, td { border: 1px solid black; padding: 2px 6px; }"

(OUT / "configuration.html").write_text(HTML_PAGE, encoding="utf-8")
(OUT / "retries.md").write_text(MARKDOWN_PAGE, encoding="utf-8")

pdf = pymupdf.open()
page = pdf.new_page()  # A4 by default
page.insert_htmlbox(pymupdf.Rect(50, 50, 545, 792), PDF_HTML, css=CSS)
# Page 2 imitates a scan: a picture of page 1 with no text layer.
picture = page.get_pixmap(dpi=150)
scan = pdf.new_page()
scan.insert_image(scan.rect, stream=picture.tobytes("png"))
pdf.subset_fonts()
pdf.save(OUT / "operations.pdf", garbage=3, deflate=True)

print(sorted(p.name for p in OUT.iterdir()), "pages in PDF:", pdf.page_count)
Terminal
python make_samples.py
Expected output
['configuration.html', 'operations.pdf', 'retries.md'] pages in PDF: 2

03. Step 2: HTML, without the page chrome

Beautiful Soup's get_text() is the tempting one-liner. The converter below does more work: it removes the parts of the page that repeat on every page, then writes each content block as Markdown.

Python · parse_html.py
from bs4 import BeautifulSoup, Tag

BOILERPLATE = ["script", "style", "nav", "header", "footer", "aside", "form"]
BLOCKS = {"h1", "h2", "h3", "h4", "h5", "h6", "p", "ul", "ol", "pre", "table"}


def html_to_markdown(html: str) -> str:
    soup = BeautifulSoup(html, "html.parser")
    for tag in soup(BOILERPLATE):
        tag.decompose()
    for tag in soup.select(".cookie-banner, [role=navigation]"):
        tag.decompose()
    for code in soup.select(":not(pre) > code"):  # inline code keeps its backticks
        code.replace_with(f"`{code.get_text()}`")
    root = soup.find("main") or soup.body or soup
    return "\n\n".join(walk(root)) + "\n"


def walk(node: Tag) -> list[str]:
    out: list[str] = []
    for child in node.find_all(True, recursive=False):
        if child.name in BLOCKS:
            out.append(convert(child))
        else:  # div, section, article ...: look inside
            out.extend(walk(child))
    return out


def text_of(el: Tag) -> str:
    return " ".join(el.get_text().split())  # collapse HTML whitespace


def convert(el: Tag) -> str:
    if el.name[0] == "h":
        return "#" * int(el.name[1]) + " " + text_of(el)
    if el.name in ("ul", "ol"):
        items = el.find_all("li", recursive=False)
        marks = ["-"] * len(items) if el.name == "ul" else [
            f"{i}." for i in range(1, len(items) + 1)]
        return "\n".join(f"{m} {text_of(li)}" for m, li in zip(marks, items))
    if el.name == "pre":
        code = el.find("code") or el
        lang = next((c[9:] for c in code.get("class", [])
                     if c.startswith("language-")), "")
        return f"```{lang}\n{code.get_text().rstrip()}\n```"  # whitespace kept
    if el.name == "table":
        rows = [[text_of(c).replace("|", "\\|") for c in tr.find_all(["th", "td"])]
                for tr in el.find_all("tr")]
        lines = ["| " + " | ".join(r) + " |" for r in rows]
        lines.insert(1, "|" + "---|" * len(rows[0]))
        return "\n".join(lines)
    return text_of(el)  # a paragraph
  • decompose() deletes the boilerplate elements and everything inside them. The selectors are site-specific: find your theme's banners, sidebars and edit this page links in the browser's developer tools.
  • Inline code becomes backticked text first, so larkspur.toml stays marked as code inside its paragraph.
  • walk() descends through wrappers such as div and section and converts only real blocks, however deeply a theme nests them.
  • Each block type has one rule: headings keep their level, list items become - or 1. lines, pre becomes fenced code with its text untouched, and tables become Markdown tables with a header row.
Python · try_html.py
import textwrap
from pathlib import Path

from bs4 import BeautifulSoup

from parse_html import html_to_markdown

html = Path("samples/configuration.html").read_text(encoding="utf-8")
naive = BeautifulSoup(html, "html.parser").get_text(" ", strip=True)
print(textwrap.fill(naive[:230], width=80), "...")
print("-" * 30)
print(html_to_markdown(html))
Terminal
python try_html.py
Expected output
Configuration · Larkspur docs We use cookies. Accept Home Install API
Configuration Larkspur reads larkspur.toml from the working directory. Workers
The workers setting controls how many jobs run at once. Default: 4 Each worker
is ...
------------------------------
# Configuration

Larkspur reads `larkspur.toml` from the working directory.

## Workers

The `workers` setting controls how many jobs run at once.

- Default: 4
- Each worker is a separate process

## Example

```toml
workers = 8
timezone = "Europe/London"

[logging]
level = "debug"
```

## Settings reference

| Setting | Default | Environment variable |
|---|---|---|
| workers | 4 | LARKSPUR_WORKERS |
| timezone | UTC | LARKSPUR_TZ |

The naive text begins with the page title, the cookie banner and the menu, runs every heading into the next paragraph and flattens the table into a stream of words. (The script is missing only because Beautiful Soup does not count script and style contents as text.) The converted version keeps every heading level, the list, the TOML sample with its blank line, and the table with its header row. Libraries such as trafilatura and markdownify cover more edge cases on whole websites; the decisions stay the same.

04. Step 3: Markdown, read by a parser

Markdown is already structured, so the job is to remove what is not content and to read the structure with a parser, not a regular expression. Front matter (the YAML block between --- lines at the top) is metadata, not text, and HTML comments are notes for editors.

Python · parse_markdown.py
import re

from markdown_it import MarkdownIt

FRONT_MATTER = re.compile(r"\A---\n.*?\n---\n", re.DOTALL)
md = MarkdownIt("commonmark")


def clean_markdown(text: str) -> str:
    text = FRONT_MATTER.sub("", text)  # YAML metadata is not content
    lines = text.splitlines()
    for tok in reversed(md.parse(text)):  # drop HTML comments, only real ones
        if tok.type == "html_block" and tok.content.startswith("<!--"):
            start, end = tok.map
            del lines[start:end]
            if 0 < start < len(lines) and not lines[start] and not lines[start - 1]:
                del lines[start]  # avoid leaving two blank lines in a row
    return "\n".join(lines).strip() + "\n"


def outline(text: str) -> list[str]:
    tokens = md.parse(text)
    return [f"{tok.tag} {tokens[i + 1].content}"
            for i, tok in enumerate(tokens) if tok.type == "heading_open"]

md.parse() returns block tokens, each with a map: the range of source lines it covers. The cleaner deletes only html_block tokens that are comments, so an <!-- inside a code sample survives. outline() lists the headings as any CommonMark renderer sees them.

Python · try_markdown.py
import re
from pathlib import Path

from parse_markdown import clean_markdown, outline

text = clean_markdown(Path("samples/retries.md").read_text(encoding="utf-8"))
print(repr(text[:60]))  # front matter and comment are gone
for heading in re.findall(r"^#{1,6} .*", text, flags=re.MULTILINE):
    print("regex: ", heading)  # the naive way
for heading in outline(text):
    print("parser:", heading)  # what a CommonMark parser sees
Terminal
python try_markdown.py
Expected output
'# Retries and failures\n\nA job fails when it raises an except'
regex:  # Retries and failures
regex:  ## Retry policy
regex:  # max_retries = 0 means: fail on the first error
regex:  ## Dead-letter queue
parser: h1 Retries and failures
parser: h2 Retry policy
parser: h2 Dead-letter queue

The regular expression reports a heading, # max_retries = 0 means: fail on the first error, that is really a comment inside the Python sample. A splitter built on it would open a new section halfway through the code and file the second half of the sample under a heading that does not exist. The parser knows the line is inside a fenced block. Use the same parser whenever you need section boundaries; the lab later in this skill does exactly that.

05. Step 4: PDF, rebuilt from positions

A PDF stores glyphs at positions on a page, not paragraphs, headings or tables; as the pypdf documentation puts it, PDF has no semantic layer. You get words and coordinates and must rebuild the rest: reading order from positions, headings from font sizes, tables from ruling lines and alignment.

Python · parse_pdf.py
import pymupdf

MIN_CHARS = 20  # a page with less text than this is probably a scan


def rows_to_markdown(rows: list[list[str | None]]) -> str:
    cells = [[" ".join((c or "").split()).replace("|", "\\|") for c in r] for r in rows]
    lines = ["| " + " | ".join(r) + " |" for r in cells]
    lines.insert(1, "|" + "---|" * len(cells[0]))
    return "\n".join(lines)


def page_to_markdown(page: pymupdf.Page) -> str:
    tables = page.find_tables().tables
    items = [(t.bbox[1], rows_to_markdown(t.extract())) for t in tables]
    for block in page.get_text("dict", sort=True)["blocks"]:
        box = pymupdf.Rect(block["bbox"])
        if block["type"] != 0 or any(box.intersects(t.bbox) for t in tables):
            continue  # an image, or text that is already in a table
        lines = block["lines"]
        text = " ".join("".join(s["text"] for s in ln["spans"]) for ln in lines)
        size = max(s["size"] for ln in lines for s in ln["spans"])
        # Font sizes stand in for heading levels; tune the thresholds per PDF family.
        prefix = "# " if size >= 22 else "## " if size >= 16 else ""
        items.append((box.y0, prefix + " ".join(text.split())))
    return "\n\n".join(text for _, text in sorted(items))
  • find_tables() looks for tables, by default from their ruling lines, and extract() returns each table as rows of cell strings, which rows_to_markdown() turns into a Markdown table with a header row.
  • get_text("dict", sort=True) returns text blocks with bounding boxes and the font size of every span, sorted top to bottom and then left to right. Blocks that overlap a table are skipped, because the table already holds their text.
  • Heading levels come from font sizes, with thresholds that suit this one family of documents. Print the sizes of a few pages before choosing yours.
  • Items go back into reading order by their top edge, which is right for one column. A two-column layout must be grouped by column first; this is where layout-analysis tools earn their keep.
Python · try_pdf.py
import pymupdf

from parse_pdf import MIN_CHARS, page_to_markdown

with pymupdf.open("samples/operations.pdf") as pdf:
    print(pdf[0].get_text().split("\n")[4:13])  # raw text layer around the table
    print("-" * 30)
    for page in pdf:
        if len(page.get_text().strip()) < MIN_CHARS:
            print(f"[page {page.number + 1}: no text layer, needs OCR]")
        else:
            print(page_to_markdown(page))
Terminal
python try_pdf.py
Expected output
['Limit', 'Default', 'Maximum', 'Workers', '4', '64', 'Retries', '3', '10']
------------------------------
# Larkspur operations sheet

The limits operators ask about most. They apply per process.

## Limits

Raise a limit only after checking memory use.

| Limit | Default | Maximum |
|---|---|---|
| Workers | 4 | 64 |
| Retries | 3 | 10 |
| Timeout (minutes) | 15 | 720 |
[page 2: no text layer, needs OCR]

In the raw text layer the table is a column of loose values, and nothing says that 64 is the maximum number of workers. The rebuilt page has its headings and a table whose rows keep their labels. The second page has no text at all, so the parser flags it instead of quietly producing an empty page.

Check licences before choosing a PDF library for a product. PyMuPDF and its add-ons pymupdf4llm and pymupdf-layout are AGPL or commercial. pypdf is BSD-licensed but does not detect tables. Docling (MIT) converts PDF, DOCX and HTML into Markdown or JSON with layout and table models, at the cost of a much larger install.

06. Step 5: Scanned pages, with OCR or a vision model

A scanned page is an image, so text extraction returns nothing. There are two ways to get its words:

  1. OCR. Tesseract is the usual open-source engine, installed as a separate program (sudo apt install tesseract-ocr, brew install tesseract); PyMuPDF calls it through get_textpage_ocr(), and OCRmyPDF adds a text layer to whole PDF files.
  2. A vision-capable model. Send the page image to a multimodal LLM and ask for Markdown, with tables and a sentence describing each figure. It handles complex layouts and charts better than classic OCR, but costs money per page and can silently change numbers or invent cells, so compare a sample with the images.

Here is the OCR route for page 2, run where Tesseract is installed:

Python · ocr_page.py
import pymupdf

with pymupdf.open("samples/operations.pdf") as pdf:
    page = pdf[1]
    textpage = page.get_textpage_ocr(language="eng", dpi=300, full=True)
    print(page.get_text(textpage=textpage, sort=True))
Terminal
python ocr_page.py
Illustrative output with PyMuPDF 2.1 and the Tesseract English data (tessdata_fast)
Larkspur operations sheet


The limits operators ask about most. They apply per process.

Limits


Raise a limit only after checking memory use.

The headings and sentences came back, but every table cell was lost, without any error. The tesseract command on the same image, in its default page-segmentation mode, did read the cells, as loose lines with stray | characters and no table structure. OCR output is plain text whose quality depends on resolution, layout and settings, so treat it as a lower-trust source: compare word counts with what you expect, check pages with tables or figures by eye, and record in the metadata that the text came from OCR.

07. Step 6: Normalise and save one record per document

The last step puts the three parsers behind one function and writes docs.jsonl. Unicode NFC normalisation gives each character one canonical form, so an é stored as one code point and an e plus a combining accent become the same string, which matters when lesson 4 hashes text into IDs. page_starts records where each PDF page begins, so a chunk can later report its page in a citation; normalising each page before measuring keeps those offsets exact.

Python · ingest.py
import json
import unicodedata
from pathlib import Path

import pymupdf

from parse_html import html_to_markdown
from parse_markdown import clean_markdown
from parse_pdf import MIN_CHARS, page_to_markdown


def normal(text: str) -> str:
    """One canonical form per character; no-break spaces become plain spaces."""
    return unicodedata.normalize("NFC", text).replace("\xa0", " ")


def parse(path: Path) -> dict:
    record = {"source": path.as_posix(), "text": "", "page_starts": [], "needs_ocr": []}
    if path.suffix == ".html":
        record["text"] = normal(html_to_markdown(path.read_text(encoding="utf-8")))
    elif path.suffix == ".md":
        record["text"] = normal(clean_markdown(path.read_text(encoding="utf-8")))
    elif path.suffix == ".pdf":
        with pymupdf.open(path) as pdf:
            for page in pdf:
                record["page_starts"].append(len(record["text"]))
                if len(page.get_text().strip()) < MIN_CHARS:
                    record["needs_ocr"].append(page.number + 1)
                else:
                    record["text"] += normal(page_to_markdown(page)) + "\n\n"
    else:
        raise ValueError(f"no parser for {path}")
    return record


with open("docs.jsonl", "w", encoding="utf-8") as out:
    for path in sorted(Path("samples").iterdir()):
        record = parse(path)
        out.write(json.dumps(record, ensure_ascii=False) + "\n")
        text = record["text"]
        fences = text.count("```") // 2
        tables = sum(line.startswith("|---") for line in text.splitlines())
        print(f"{path.name:<19} {len(text):>3} chars  code: {fences}  tables: {tables}"
              f"  OCR pages: {record['needs_ocr']}")
Terminal
python ingest.py
Expected output
configuration.html  439 chars  code: 1  tables: 1  OCR pages: []
operations.pdf      269 chars  code: 0  tables: 1  OCR pages: [2]
retries.md          388 chars  code: 1  tables: 0  OCR pages: []

Every document now has the same shape whatever its format, with code blocks and tables intact, and the PDF record says openly that page 2 is still missing.

08. Common mistakes

09. Check your understanding

Practice check · 3 questions

Parsing decisions

Diagnose three parsing problems. Each question has one best answer.

Q1. A 40-page vendor PDF parses without errors, but 12 pages yield fewer than 20 characters each, although they look full of text when you open them. What is the most likely explanation?
Q2. A splitter cuts Markdown wherever a line starts with #. On a page with a Bash sample it creates a section called '# install the CLI first'. What is the robust fix?
Q3. Text from a two-column PDF comes out as the first line of the left column, then the first line of the right column, and so on. Which change addresses this?
Practice only: not graded, not saved, not evidence.

10. Apply it

Run this pipeline on the documentation set you chose for the practice project.

  1. If it is Markdown, use clean_markdown() and outline(), and compare the outline of three pages with the rendered website.
  2. If the docs exist only as HTML, fetch three pages (respect the site's robots.txt and licence), find the selectors of its menu, banners and footer in the developer tools, and add them to BOILERPLATE or the select() call.
  3. Write docs.jsonl and inspect one record by eye: every heading present, code samples identical to the source character for character, tables with a header row.
  4. If the set includes PDFs, list the pages that need OCR and decide which route you will take for them.

11. Review prompt

Without looking back:

  1. List what you remove and what you keep when you convert a documentation page from HTML, and say why.
  2. Explain why a regular expression is not enough to find the headings of a Markdown file.
  3. Name three things a PDF does not store that you have to reconstruct, and how you reconstruct each.
  4. How do you detect a scanned page, what are the two ways to get its text, and what is one risk of each?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check