Trafilatura exposes a set of utility functions used internally during extraction that are also useful when you need fine-grained control over text processing, validation, caching, or deduplication. This page documents the public-facing helpers spread acrossDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/adbar/trafilatura/llms.txt
Use this file to discover all available pages before exploring further.
trafilatura.utils, trafilatura.xml, trafilatura.readability_lxml, trafilatura.meta, and trafilatura.deduplication.
utils.sanitize()
trafilatura.utils.sanitize cleans and normalises a text string by removing HTML space entities ( , , ), stripping control characters, collapsing redundant whitespace, and filtering blank lines. Optionally, it can process the string as a single logical line rather than splitting on newlines.
Parameters
The input string to clean. If
None is passed, None is returned.When
True, internal newlines and spacing are not collapsed. Useful for
preserving the layout of <pre> / <code> blocks.When
True, the entire string is treated as a single line and leading/trailing
spaces adjacent to the content are preserved for inline formatting contexts.str | None — the cleaned string, or None when text is None or consists entirely of whitespace after cleaning.
Example
utils.trim()
trafilatura.utils.trim strips all leading and trailing whitespace from a string and collapses any internal runs of whitespace (including Unicode spaces and newlines) into single ASCII spaces. It is LRU-cached up to 1 024 unique inputs.
Parameters
The string to normalise. Returns
"" on None or non-string input rather
than raising an exception.str — the trimmed string. Never returns None.
Example
utils.decode_file()
trafilatura.utils.decode_file converts raw bytes to a Unicode string. It handles compressed payloads transparently (gzip, zstandard, brotli, zlib), auto-detects the character encoding using cchardet (if installed) and charset-normalizer, and falls back to a UTF-8 decode with replacement characters if all else fails.
Parameters
The raw file content to decode. If a
str is passed it is returned unchanged,
making the function safe to call unconditionally.str — a decoded Unicode string.
Example
Compression detection is based on magic bytes (file signatures), not HTTP
headers. This makes it safe to use on files saved to disk where headers are
unavailable.
xml.xmltotxt()
trafilatura.xml.xmltotxt serialises an lxml element tree produced by Trafilatura’s internal extraction pipeline to a plain-text or Markdown string. When include_formatting=True the function deep-copies the tree before modifying it, so the caller’s element is never mutated.
Parameters
The root element to serialise. Returns an empty string when
None.When
True, inline formatting tags (<hi>, <del>, <ref>, <code>) are
converted to their Markdown equivalents and LaTeX math delimiters are
rewritten to $…$ / $$…$$. When False, only plain text is emitted.str — the serialised text content.
Example
xml.validate_tei()
trafilatura.xml.validate_tei checks whether an lxml element tree conforms to the TEI Corpus DTD bundled with Trafilatura (trafilatura/data/tei_corpus.dtd). The DTD object is loaded lazily and cached as a module-level global after the first call.
Parameters
The root element of the document to validate. Typically the
<TEI> element
produced by trafilatura.xml.build_tei_output().bool — True if the document validates, False otherwise. A logging.WARNING is emitted that includes the first DTD error when validation fails.
Example
readability_lxml.is_probably_readerable()
trafilatura.readability_lxml.is_probably_readerable is a Python port of Mozilla’s isProbablyReaderable function from Readability.js. It gives a fast, cheap estimate of whether a page is worth attempting full extraction on, without actually running the extraction pipeline.
The heuristic scores visible <p>, <pre>, and <article> nodes (and parents of <div><br> constructs) by their text length, skipping nodes that are hidden or whose class/id attributes match a list of unlikely-candidate patterns. When the cumulative score exceeds a configurable threshold the page is considered readerable.
Parameters
The HTML document to evaluate. The formal type annotation is
HtmlElement; in
practice the argument is passed through trafilatura.utils.load_html()
internally, so raw HTML strings and bytes objects are also accepted.Optional dictionary to override internal thresholds:
min_content_length(int, default140): minimum text length for a node to contribute to the score.min_score(int, default20): cumulative score threshold above which the page is considered readerable.visibility_checker(callable, defaultis_node_visible): a function(HtmlElement) -> boolused to skip hidden nodes.
bool — True if the page is likely to contain extractable article content.
Example
meta.reset_caches()
trafilatura.meta.reset_caches clears every LRU cache used internally by Trafilatura and its dependencies (htmldate, courlan, justext) and triggers a garbage-collection cycle. Calling it periodically in long-running processes prevents unbounded memory growth from cached function results.
Parameters
None. The function takes no arguments. ReturnsNone.
When to use
Long-running crawlers
Call
reset_caches() every N documents or every few hours to keep RSS
steady when processing millions of pages.Memory-constrained environments
Call before processing a new large batch to reclaim memory held by cached
text fragments from the previous batch.
Example
justext.core.define_stoplist- All
htmldateandcharset_normalizercaches (viahtmldate.meta.reset_caches) - All
courlancaches (viacourlan.meta.clear_caches) deduplication.is_similar_domainutils.line_processingutils.return_printables_and_spacesutils.trimdeduplication.LRU_TEST(the deduplication LRU store)deduplication._vector_to_add
deduplication.duplicate_test()
trafilatura.deduplication.duplicate_test checks whether the concatenated text content of an lxml element has been seen too many times during the current session. It uses an LRU cache (LRU_TEST) to track occurrence counts. Text shorter than options.min_duplcheck_size is always allowed through without a cache lookup.
Parameters
The element whose text content (all descendant text nodes joined) is tested.
The test string is produced by
trim(" ".join(element.itertext())).The current extraction options. Two fields are used:
options.min_duplcheck_size— strings shorter than this are not checked.options.max_repetitions— the number of allowed occurrences before the element is considered a duplicate.
bool — True when the element is a duplicate and should be discarded, False when it should be kept.
Example
The deduplication cache is process-wide and persistent for the lifetime of the
Python process. Call
trafilatura.meta.reset_caches() to clear it between
unrelated crawl jobs.deduplication.content_fingerprint()
trafilatura.deduplication.content_fingerprint computes a 64-bit Simhash fingerprint of the meaningful content tokens in a string and returns it as a hexadecimal string. Near-duplicate texts will produce very similar (low Hamming distance) hashes, making this useful for cross-document similarity checks.
- Tokenises the input, strips punctuation, and filters to alphanumeric tokens via
sample_tokens(). - Computes a BLAKE2b hash for each token.
- Accumulates a sign vector (Charikar’s Simhash algorithm) over the token hashes.
- Returns the resulting integer as a hex string.
Parameters
The text to fingerprint. Punctuation is stripped and only alphanumeric tokens
contribute to the hash, so formatting differences do not affect the result.
str — a hexadecimal Simhash fingerprint.