Skip to main content

betterhtmlchunking

Banner

CI PyPI version Python versions License: MIT DeepWiki Discord

A Python library for intelligently chunking HTML documents into structured, size-limited segments based on DOM tree analysis.

Overview

This library processes HTML content to split it into semantically coherent chunks while respecting specified size constraints. It analyzes the DOM structure to identify optimal split points, preserving contextual information and document hierarchy.

Key Features

  • Custom DOM tree representation.
  • Configurable chunk size limits (counting by text or HTML length).
  • Intelligent region-of-interest detection.
  • Dual output formats: HTML and plain text chunks.
  • Preservation of structure relationships.
  • Customizable tag filtering.

Installation

pip install betterhtmlchunking

Dependencies

  • Python 3.11+
  • attrs
  • treelib
  • parsel
  • parsel-text
  • lxml
  • attrs-strict

Usage

Quick Start

from betterhtmlchunking import chunk_html

chunks = chunk_html(html_content, max_length=4096)  # by="text" measures the text instead
for chunk in chunks:
    print(chunk.index, len(chunk.html), chunk.text[:80])

Each Chunk is immutable and has index, html, text and xpaths (the positional XPaths of its pieces). chunk_html takes the same options as DomRepresentation as keyword arguments (tag_list_to_filter_out, html_unescape, fix_mojibake). For access to the DOM tree and the regions of interest, use DomRepresentation directly, as below.

Basic Example

from betterhtmlchunking import DomRepresentation
from betterhtmlchunking.main import ReprLengthComparisonBy
from betterhtmlchunking.main import tag_list_to_filter_out

html_content = """
<html>
  <body>
    <div id="content">
      <h1>Document Title</h1>
      <p>First paragraph...</p>
      <p>Second paragraph...</p>
    </div>
  </body>
</html>
"""

# Create document representation with 20 character chunks.
dom_repr = DomRepresentation(
    MAX_NODE_REPR_LENGTH=20,
    website_code=html_content,
    repr_length_compared_by=ReprLengthComparisonBy.HTML_LENGTH
    # tag_list_to_filter_out=["/head", "/header", "..."]  # By default tag_list_to_filter_out is used.
)
dom_repr.start()

# Render HTML:
for idx in dom_repr.tree_regions_system.sorted_roi_by_pos_xpath:
    print("*" * 50)
    print(f"IDX: {idx}")
    roi_html_render: str =\
        dom_repr.render_system.get_roi_html_render_with_pos_xpath(
            roi_idx=idx
        )
    print(roi_html_render)


# Render text:
for idx in dom_repr.tree_regions_system.sorted_roi_by_pos_xpath:
    print("*" * 50)
    print(f"IDX: {idx}")
    roi_text_render: str =\
        dom_repr.render_system.get_roi_text_render_with_pos_xpath(
            roi_idx=idx
        )
    print(roi_text_render)

Render output (HTML):

**************************************************
IDX: 0
<h1>
 Document Title
</h1>

**************************************************
IDX: 1
<p>
 First paragraph...
</p>

**************************************************
IDX: 2
<p>
 Second paragraph...
</p>

Render output (text):

**************************************************
IDX: 0
Document Title

**************************************************
IDX: 1
First paragraph...

**************************************************
IDX: 2
Second paragraph...

Configuration

Key Parameters

  • MAX_NODE_REPR_LENGTH: Maximum allowed length for each chunk (in characters)
  • repr_length_compared_by: Length calculation method:
    • ReprLengthComparisonBy.HTML_LENGTH: HTML source length
    • ReprLengthComparisonBy.TEXT_LENGTH: Rendered text length
  • website_code: Input HTML content, as an already decoded str. Text that contains lone surrogates (for example, bytes decoded with errors="surrogateescape") raises ValueError, because lxml would silently drop everything after the first one.
  • tag_list_to_filter_out: Elements to remove before chunking, as xpath steps such as /head or /body/aside (defaults to tag_list_to_filter_out from betterhtmlchunking.main). Each entry matches whole steps at any depth: /p removes <p> elements but not <pre>, and /b does not touch <body>. A step without an index matches any position; /div[2] matches only that one. A removed element takes its contents with it, but the text right after it is kept.
  • html_unescape: Whether to HTML-unescape website_code before parsing. With None (the default) this happens only when the input looks like an escaped document: no real tags, but escaped ones such as &lt;p&gt; (for example, HTML stored inside JSON). True always unescapes and False never does. Unescaping real HTML would turn its escaped text, such as code samples and attribute values, into markup.

Advanced Features

# Access the DOM tree structure
tree = dom_repr.tree_representation.tree

# Get node metadata:
for node in tree.all_nodes():
    if node.data is not None:
        print(f"XPath: {node.identifier}")
        print(f"Text length: {node.data.text_length}")
        print(f"HTML length: {node.data.html_length}")

How It Works

  1. DOM Parsing

    • Builds a tree representation of the HTML document.
    • Calculates metadata (text length, HTML length) for each node.
  2. Region Detection

    • Uses Breadth First Search (BFS) to traverse the DOM tree in a level-order fashion, ensuring that each node is processed systematically.
    • Combines nodes until the specified size limit is reached. No chunk goes over the limit (the \n that joins its pieces included), except a single leaf element or run of text that is larger than the limit on its own and cannot be split without cutting text.
    • Text placed directly inside an element (around or between its children) is a unit of its own, so splitting an element never drops text. Regions list their pieces by positional XPath; text pieces use the standard text-node form, e.g. /html/body/p/text()[2].
    • Preserves parent-child relationships to maintain contextual integrity.
  3. Chunk Generation

    • Creates HTML chunks with original markup.
    • Generates parallel text-only chunks.
    • Maintains chunk order based on document structure.

The actual practice (Feb. 2025) is to use plain-text or token-based chunking strategies, primarily aimed at keeping prompts within certain token limits for large language models. This approach is ideal for quick semantic retrieval or QA tasks on unstructured text.

By contrast, betterhtmlchunking preserves the HTML DOM structure, calculating chunk boundaries based on each node’s text or HTML length. This approach is especially useful when you want to:

  • Retain or leverage the hierarchical relationships in the HTML (e.g., headings, nested divs)
  • Filter out undesired tags or sections (like <script> or <style>)
  • Pinpoint exactly where each chunk originated in the document (via positional XPaths)

You can even combine the two techniques if you need both structured extraction (via betterhtmlchunking) and LLM-friendly text chunking (via LangChain) for advanced tasks such as summarization, semantic search, or large-scale QA pipelines.

CLI

The package ships with a command line interface built with Typer. You can pipe HTML to the tool and work with chunks in multiple ways.

Basic Usage - Single Chunk

Get a specific chunk as HTML:

cat input.html | betterhtmlchunking --max-length 32768 --chunk-index 0 > chunk.html

By default the command reads from stdin, processes chunks up to a maximum length of 32,768 characters, and prints the HTML corresponding to chunk index 0 to stdout.

Input Encoding

stdin is decoded as UTF-8 by default. For documents in another encoding, pass it with --encoding:

cat legacy.html | betterhtmlchunking --encoding latin-1 --max-length 32768

Input that is not valid in the chosen encoding is rejected with an error (exit code 1) instead of being processed partially.

Escaped Input

HTML that arrives escaped (&lt;p&gt;Hello&lt;/p&gt;, as when it is stored inside JSON) is unescaped automatically, as long as it has no real tags. Use --html-unescape or --no-html-unescape to force either behavior:

cat escaped.txt | betterhtmlchunking --html-unescape --max-length 32768

List All Chunks

See how many chunks are created and their sizes without processing the full content:

cat input.html | betterhtmlchunking --max-length 32768 --list-chunks

Output:

Total chunks: 5
Chunk 0: 28543 chars HTML, 12834 chars text
Chunk 1: 31245 chars HTML, 15234 chars text
Chunk 2: 19823 chars HTML, 9234 chars text
...

Save All Chunks

Extract all chunks to separate files:

cat input.html | betterhtmlchunking --max-length 32768 --all-chunks --output-dir ./chunks

This creates chunk_0.html, chunk_1.html, etc. in the specified directory.

Text-Only Output

Get plain text content without HTML markup:

# Single chunk as text
cat input.html | betterhtmlchunking --max-length 32768 --chunk-index 0 --text-only > chunk.txt

# All chunks as text files
cat input.html | betterhtmlchunking --max-length 32768 --all-chunks --text-only --output-dir ./chunks

This creates chunk_0.txt, chunk_1.txt, etc. with plain text content.

JSON Output

Get structured JSON output with all chunks and metadata:

cat input.html | betterhtmlchunking --max-length 32768 --format json > output.json

Output format:

{
  "total_chunks": 5,
  "max_length": 32768,
  "compared_by": "html",
  "chunks": [
    {
      "index": 0,
      "html": "<h1>...</h1>",
      "text": "...",
      "html_length": 28543,
      "text_length": 12834
    },
    ...
  ]
}

This is useful for programmatic processing. You can pipe the output to tools like jq or process it with scripts:

# Extract only text from all chunks
cat input.html | betterhtmlchunking --format json | jq -r '.chunks[].text'

# Get chunk count
cat input.html | betterhtmlchunking --format json | jq '.total_chunks'

# Filter chunks by size
cat input.html | betterhtmlchunking --format json | jq '.chunks[] | select(.text_length > 1000)'

With nushell

If you use nushell, the JSON output parses into a native table you can query directly, with no manual JSON handling:

# Chunks as a table with their sizes
open --raw input.html | betterhtmlchunking --format json | from json | get chunks | select index html_length text_length

# Filter chunks by size
open --raw input.html | betterhtmlchunking --format json | from json | get chunks | where text_length > 1000

# Chunk count
open --raw input.html | betterhtmlchunking --format json | from json | get total_chunks

Verbose Mode

Enable progress logging with --verbose. Logs are written to stderr so they don't interfere with chunk output:

cat input.html | betterhtmlchunking --max-length 32768 --all-chunks --output-dir ./chunks --verbose

Maximal Verbose Mode

For detailed inspection of the DOM, nodes, ROIs, and chunk lengths, use --maximal-verbose. This logs:

  • Total DOM nodes and their HTML/text lengths
  • Each ROI (region of interest) with constituent node XPaths and lengths
  • Final chunk HTML and text sizes
cat input.html | betterhtmlchunking --max-length 32768 --chunk-index 0 --maximal-verbose > chunk.html 2> logs.txt
  • chunk.html contains the selected chunk HTML.
  • logs.txt captures all detailed logging information.

This mode is useful for debugging, testing, or analyzing how the document is split into chunks.

CLI Options Summary

Option Short Description
--max-length -l Maximum length for each chunk (default: 32768)
--chunk-index -c Index of specific chunk to output (default: 0)
--list-chunks List all chunks with their sizes
--all-chunks Output all chunks (requires --output-dir)
--output-dir -o Directory to save chunks when using --all-chunks
--text-only Output plain text instead of HTML
--format -f Output format: json for structured JSON output
--text Compare length using text instead of HTML
--verbose -v Enable progress logging
--maximal-verbose Enable detailed debug logging

License

MIT License

Contributing

Feel free to open issues or submit pull requests if you have suggestions or improvements.

Metadata

Release files for betterhtmlchunking 0.14.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for betterhtmlchunking 0.14.0
File Size Uploaded Provenance Actions
betterhtmlchunking-0.14.0.tar.gz 42.3 kB With provenance Details for betterhtmlchunking-0.14.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for betterhtmlchunking 0.14.0
File Interpreter ABI Platform Actions
betterhtmlchunking-0.14.0-py3-none-any.whl Python 3 none any Details for betterhtmlchunking-0.14.0-py3-none-any.whl

Total release size: 67.9 kB

Release files / betterhtmlchunking-0.14.0.tar.gz

Download URL betterhtmlchunking-0.14.0.tar.gz
Size 42.3 kB
Tags Source
SHA-256 checksum
How to use checksums
28c2f46e555b1a819a7b9fcc13ee54aa45458fa9cdfc613821e368315b42dbfb
BLAKE2b-256 checksum
How to use checksums
31d10a064d7e71235b1065d8c390ec8d15cb5bb03d046884a98a5c19e37c1fda
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Release files / betterhtmlchunking-0.14.0-py3-none-any.whl

Download URL betterhtmlchunking-0.14.0-py3-none-any.whl
Size 25.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7b05843374b718a18b43f9840c19db154d0ee5bd9fe00a8623bb001ffd7869c9
BLAKE2b-256 checksum
How to use checksums
874622cbd8a02cc5cefbf6119a8c01e4c5a9089910e68a2f5065d1442e6b4a36
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

Security for betterhtmlchunking 0.14.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for betterhtmlchunking-0.14.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 26, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page