Trafilatura’s extraction module provides a suite of functions for pulling clean text and metadata from HTML documents. Whether you need a simple string result, a structured Python object, or just the raw text, these functions cover every use case — from quick one-liners to fully configured pipelines.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.
extract()
The primary entry point for text extraction. Takes an HTML document in any supported form and returns the extracted content as a formatted string, or None if extraction fails or the document doesn’t meet quality thresholds.
The HTML input to extract from. Accepts a Unicode string, raw bytes, or an already-parsed
lxml.html.HtmlElement tree.URL of the webpage. Used for metadata extraction and resolving relative links.
An optional identifier added to the document metadata (available in structured output formats like XML, JSON, and CSV).
Skip the fallback extraction algorithms (readability and jusText) and use only Trafilatura’s main extractor. Faster but may produce shorter or lower-quality output for difficult pages.
Deprecated. Use
fast=True instead. Raises a DeprecationWarning.Prefer shorter, higher-confidence extractions. Reduces false positives at the cost of possibly missing some content.
Prefer more text even when uncertain. Useful when missing content is worse than including some noise.
Extract user comments from comment sections along with the main article body.
The serialization format for the returned string. One of:
"txt"— plain text (default)"markdown"— Markdown with heading and emphasis preservation"html"— cleaned HTML"json"— JSON object"csv"— tab-separated values"xml"— Trafilatura XML format"xmltei"— TEI-compliant XML
Validate the output against the TEI standard. Only applicable when
output_format="xmltei".Discard documents that are not written in the specified language. Accepts an ISO 639-1 two-letter language code (e.g.,
"en", "de"). Requires py3langid to be installed for full functionality.Extract text from HTML
<table> elements.Include image elements in the extraction (experimental). Captures
src and alt attributes.Preserve structural formatting elements such as bold, italic, and headings. Rendered as Markdown in text formats; kept as tags in XML formats. Ignored for JSON output.
Keep hyperlinks and their targets in the output (experimental).
Filter out duplicate text segments and previously seen documents using a fingerprint cache.
A dictionary of keyword arguments forwarded to htmldate for date extraction. For example:
{"original_date": True, "extensive_search": False}.Prepend extracted metadata (title, author, date, etc.) to the output string. For
"txt" and "markdown" formats this is rendered as a YAML front matter block.Return
None and discard documents that are missing any of the three essential metadata fields: date, title, or url.Deprecated. Raises a
ValueError when set. Configure tree size limits via the settings file instead.A set of URLs to exclude. Documents whose resolved URL appears in this set are discarded and
None is returned.A set of author name strings to suppress. Matching author values are removed from the extracted metadata.
Path to a
.cfg configuration file that overrides the default Trafilatura settings (timeouts, size limits, etc.).One or more XPath expressions. Matching elements are removed from the parse tree before extraction begins. Useful for stripping site-specific boilerplate.
A
configparser.ConfigParser instance with Trafilatura settings. Superseded by options when both are provided.A pre-built
trafilatura.settings.Extractor object. When provided, all individual keyword arguments are ignored in favour of the options object.str | None — The extracted content in the chosen format, or None if extraction fails.
Examples
bare_extraction()
A lower-level extraction function that returns a Document object instead of a serialized string. The Document.body attribute is a live lxml element tree, allowing further programmatic manipulation before serialization.
HTML content as a Unicode string, bytes, or a pre-parsed
lxml.html.HtmlElement.URL of the source page, used for metadata extraction and relative link resolution.
Skip fallback extractors (readability, jusText). Faster with potentially less complete output.
Deprecated. Use
fast=True instead.Prefer shorter, higher-confidence results.
Prefer more text, even if uncertain.
Include comment sections in the extraction.
Serialization format. Defaults to
"python" which leaves body as a raw lxml element. Other valid values are the same as extract().ISO 639-1 language code. Discards documents in other languages.
Include
<table> content in extraction.Include image metadata (experimental).
Preserve formatting tags (bold, italic, headings).
Preserve hyperlinks (experimental).
Filter duplicates using a content fingerprint.
Parameters forwarded to htmldate for date extraction.
Extract and populate metadata fields on the
Document object.Return
None when date, title, or url are missing.Deprecated. Raises a
ValueError when set. Configure tree size limits via the settings file instead.Set of URLs to exclude from results.
Set of author names to suppress.
Deprecated. Use
document.as_dict() instead.XPath expression(s) for elements to remove before extraction.
Configuration object for Trafilatura settings.
Pre-built
Extractor options object. Overrides all individual parameters.Document | None — a Document object, or None on failure.
The Document object
| Attribute | Type | Description |
|---|---|---|
title | str | None | Page title |
author | str | None | Author name(s) |
url | str | None | Canonical URL |
hostname | str | None | Domain name |
description | str | None | Meta description |
sitename | str | None | Publisher / site name |
date | str | None | Publication date (ISO format) |
categories | list[str] | None | Article categories |
tags | list[str] | None | Article tags or keywords |
fingerprint | str | None | Content fingerprint hash |
id | str | None | Record identifier |
license | str | None | Content license (e.g. CC-BY) |
language | str | None | Detected language code |
image | str | None | Featured image URL |
pagetype | str | None | Page type classification |
body | lxml._Element | Extracted content as an lxml element tree |
comments | str | None | Extracted comments as plain text |
commentsbody | lxml._Element | Extracted comments as an lxml element tree |
text | str | None | Serialized text content |
document.as_dict() to convert the object to a plain Python dictionary.
Examples
extract_with_metadata()
A convenience wrapper around extract() that always extracts metadata and returns a Document object instead of a plain string. Equivalent to calling extract() with with_metadata=True but returning the full Document rather than document.text.
HTML input as a string, bytes, or a pre-parsed lxml tree.
Source URL for metadata extraction and link resolution.
Optional record identifier written to
document.id.Skip fallback extractors.
Prefer fewer, higher-confidence results.
Prefer more text, even when uncertain.
Include comment sections in the output.
Format for
document.text. Same options as extract().Validate TEI XML output (only relevant when
output_format="xmltei").ISO 639-1 code. Documents in other languages are discarded.
Extract table content.
Include image metadata (experimental).
Preserve formatting elements.
Preserve hyperlinks (experimental).
Filter duplicate documents.
Parameters for htmldate date extraction.
URLs to exclude.
Author names to suppress.
Path to a Trafilatura settings
.cfg file.XPath expressions for elements to prune before extraction.
Configuration object.
Pre-built extractor options. Overrides all individual parameters.
Document | None
Example
extract_metadata()
Extracts only the metadata of a web page — title, author, date, URL, description, etc. — without performing full text extraction. Useful when you need structured metadata without the overhead of content analysis.
The HTML document as a string or a pre-parsed
lxml.html.HtmlElement tree.A previously known URL for the document. Used as a fallback when the canonical URL cannot be extracted from the HTML itself.
A dictionary of parameters forwarded to htmldate for publication date extraction. If
None, defaults are applied with extensive=True.Enable extensive date search, which tries more extraction strategies at the cost of some performance.
A set of author name strings to exclude from the metadata output.
Document — always returns a Document instance (never None). Fields will be None when the corresponding metadata cannot be found.
Example
html2txt()
A simple utility that strips all HTML tags and returns the raw text content of a document. Unlike extract(), this function performs no content analysis or quality filtering — it returns everything.
The HTML input as a Unicode string or a pre-parsed
lxml.html.HtmlElement tree.Remove potentially undesirable elements (scripts, styles, navigation, etc.) before text extraction. Set to
False to keep all content including boilerplate.str — the extracted text as a single string, with whitespace normalized. Returns an empty string if parsing fails.
Examples
baseline()
A minimal, dependency-free extraction function that uses simple heuristics to find the main text. It tries (in order): JSON-LD articleBody, <article> elements, paragraph tags, and finally the full body text. Primarily used as an internal fallback within the main extraction pipeline.
HTML code as a binary string, Unicode string, or parsed
lxml.html.HtmlElement.lxml._Element— a<body>element containing the extracted paragraphs as<p>childrenstr— the main text content as a plain stringint— the character length of the extracted text