Trafilatura’s Python API lets you extract the main text, comments, and metadata from HTML documents with a single function call. All core functions accept raw HTML strings, LXML element trees, or response objects, and return clean text (or structured data) in your chosen format.Documentation 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.
Import Patterns
Extraction Functions
extract()
The primary function. Wraps the full extraction pipeline and returns a string in the chosen output format, or None if extraction fails.
Raw HTML string, bytes, or a pre-parsed LXML element tree.
URL of the page. Improves metadata extraction (e.g. date from URL) and converts relative links to absolute.
Assign a custom ID string to the extracted document. Stored in the
id field of the output metadata.One of
"csv", "html", "json", "markdown", "txt", "xml", "xmltei".Extract and include metadata fields in the output.
Discard documents that are missing title, URL, or date.
Extract comment sections alongside the main text.
Extract text inside HTML
<table> elements.Preserve
<b>, <strong>, <i>, <em>, etc. Implied True when output_format="markdown".Keep link targets from
href attributes (experimental).Keep image sources (
alt, src, title from <img>) (experimental).Prefer fewer but more accurate results (less noise).
Prefer more text even when uncertain (higher coverage).
Skip fallback extraction algorithms (~2× faster).
ISO 639-1 two-letter code (e.g.
"de"). Discards documents not matching the target language. Requires trafilatura[all].Validate the XML-TEI output against the TEI standard. Only takes effect when
output_format="xmltei".Remove duplicate segments and documents.
Custom parameters forwarded to
htmldate. See date extraction.XPath expression(s) to prune specific elements before extraction.
Pass a pre-configured
Extractor instance to override all individual parameters.bare_extraction()
Returns a Document object (or None) instead of a formatted string. Useful for working with extracted data programmatically. Call .as_dict() to get a plain Python dictionary.
Document object exposes these attributes:
title, author, url, hostname, description, sitename, date, categories, tags, fingerprint, id, license, body, comments, commentsbody, raw_text, text, language, image, pagetype, filedate
bare_extraction() also accepts output_format="python" (the default for this function). To get a formatted string output, pass any of the standard format strings such as "json" or "xml".extract_with_metadata()
Convenience wrapper around extract() that always returns a Document object (with with_metadata implicitly set to True) instead of a plain string. Useful when you need both the formatted text and the metadata in a single call.
extract_with_metadata() accepts the same parameters as extract() (except with_metadata and only_with_metadata, which are fixed). The returned Document object’s .text attribute holds the formatted string output.
html2txt()
Extracts all text from an HTML document, maximizing recall. Use as a last resort when extract() produces no output. Does not consider document structure or context.
baseline()
A faster alternative that targets text paragraphs and JSON-LD metadata. Returns a tuple of (body_element, text_string, text_length).
Output Format Selection
Set theoutput_format parameter on extract() to control output structure. Valid values are "txt" (default), "markdown", "json", "csv", "html", "xml", and "xmltei".
Combining
"txt" or "csv" formats with include_formatting=True or include_links=True triggers Markdown output. The include_formatting parameter has no effect on JSON output.Including and Excluding HTML Elements
Text Elements
Structural Elements
The extraction heuristics adapt to the presence of certain elements. If results seem off, try removing a constraint (e.g. remove
include_formatting=True) to improve accuracy.Precision and Recall Presets
Adjust the trade-off between accuracy and coverage usingfavor_precision or favor_recall.
- Precision: use when output contains too much noise. You can additionally pass
prune_xpathto remove specific elements by XPath. - Recall: use when parts of the document are missing from output. If content is still missing, see the troubleshooting guide.
Language Filtering
Pass an ISO 639-1 two-letter code to discard documents whose detected language does not match. Requires thetrafilatura[all] extra and the py3langid package.
Language detection uses py3langid. If the language identification component is not installed, this filter is silently skipped.Install with:
pip install trafilatura[all]Fast Mode
Bypass fallback algorithms to approximately double extraction speed.Using the Extractor Class
Available from version 1.9 onwards. Provides a single object to configure all extraction parameters, useful for batch processing where the same settings are reused across many documents.
Extractor accepts all the same keyword arguments as extract(), including output_format, fast, precision, recall, comments, formatting, links, images, tables, dedup, lang, url, with_metadata, only_with_metadata, tei_validation, author_blacklist, url_blacklist, and date_params.
Metadata Options
"txt" or "markdown" format with with_metadata=True, a YAML front-matter header is prepended to the output:
Date Extraction Params
Dates are extracted via the external htmldate library. You can pass custom parameters using thedate_extraction_params dictionary:
Memory Management
Trafilatura uses LRU caches internally to speed up repeated operations. In long-running or large-scale applications these caches may grow large. Callreset_caches() periodically to release memory.
Input Types
Raw HTML Strings
LXML Element Trees
Pass a pre-parsedlxml.html element directly:
BeautifulSoup Objects
Convert a BeautifulSoup tree to LXML format before passing it to Trafilatura:Response Objects
Usefetch_response() to capture the final redirect URL and pass it directly:
Guessing Extractability
is_probably_readerable() is ported from Mozilla’s Readability.js (available from version 1.10). It provides a fast heuristic check to determine whether a page likely contains extractable main text.
Deprecations
The following functions and parameters are deprecated and should not be used in new code:| Deprecated | Replacement |
|---|---|
process_record() | extract() |
csv_output, json_output, tei_output, xml_output params | output_format parameter |
bare_extraction(as_dict=True) | bare_extraction() → .as_dict() |
no_fallback parameter | fast=True |
max_tree_size parameter | settings.cfg config file |
fetch_url() decode argument | fetch_response() |
decode_response() in utils | decode_file() |
with_metadata (old meaning) | only_with_metadata (only docs with required metadata) |