Skip to main content

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.

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.

Import Patterns

# Core extraction functions
from trafilatura import extract, bare_extraction, extract_with_metadata, html2txt, baseline

# Downloads
from trafilatura import fetch_url, fetch_response

# Settings class for batch configuration
from trafilatura.settings import Extractor

# Readability check
from trafilatura.readability_lxml import is_probably_readerable

# Memory management
from trafilatura.meta import reset_caches

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.
from trafilatura import fetch_url, extract

url = "https://github.blog/2019-03-29-leader-spotlight-erin-spiceland/"
downloaded = fetch_url(url)

# plain text output (default)
result = extract(downloaded)

# XML output with metadata
result = extract(downloaded, output_format="xml", with_metadata=True)

# pass the URL to enable relative-to-absolute link conversion and date extraction from URL
result = extract(downloaded, url=url)
Full signature (key parameters):
filecontent
str | HtmlElement
required
Raw HTML string, bytes, or a pre-parsed LXML element tree.
url
str
default:"None"
URL of the page. Improves metadata extraction (e.g. date from URL) and converts relative links to absolute.
record_id
str
default:"None"
Assign a custom ID string to the extracted document. Stored in the id field of the output metadata.
output_format
str
default:"txt"
One of "csv", "html", "json", "markdown", "txt", "xml", "xmltei".
with_metadata
bool
default:"False"
Extract and include metadata fields in the output.
only_with_metadata
bool
default:"False"
Discard documents that are missing title, URL, or date.
include_comments
bool
default:"True"
Extract comment sections alongside the main text.
include_tables
bool
default:"True"
Extract text inside HTML <table> elements.
include_formatting
bool
default:"None"
Preserve <b>, <strong>, <i>, <em>, etc. Implied True when output_format="markdown".
Keep link targets from href attributes (experimental).
include_images
bool
default:"False"
Keep image sources (alt, src, title from <img>) (experimental).
favor_precision
bool
default:"False"
Prefer fewer but more accurate results (less noise).
favor_recall
bool
default:"False"
Prefer more text even when uncertain (higher coverage).
fast
bool
default:"False"
Skip fallback extraction algorithms (~2× faster).
target_language
str
default:"None"
ISO 639-1 two-letter code (e.g. "de"). Discards documents not matching the target language. Requires trafilatura[all].
tei_validation
bool
default:"False"
Validate the XML-TEI output against the TEI standard. Only takes effect when output_format="xmltei".
deduplicate
bool
default:"False"
Remove duplicate segments and documents.
date_extraction_params
dict
default:"None"
Custom parameters forwarded to htmldate. See date extraction.
prune_xpath
str | list[str]
default:"None"
XPath expression(s) to prune specific elements before extraction.
options
Extractor
default:"None"
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.
from trafilatura import bare_extraction, fetch_url

downloaded = fetch_url("https://www.example.org/article")

# returns a Document object
doc = bare_extraction(downloaded)

# access attributes directly
print(doc.title)
print(doc.date)
print(doc.text)

# convert to a plain dict
data = doc.as_dict()
print(data["title"], data["url"])
The 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.
from trafilatura import extract_with_metadata, fetch_url

downloaded = fetch_url("https://www.example.org/article")

# returns a Document object with text attribute containing formatted output
doc = extract_with_metadata(downloaded, output_format="txt")

if doc is not None:
    print(doc.title)
    print(doc.author)
    print(doc.text)   # formatted text in the chosen output_format
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.
from trafilatura import html2txt, fetch_url

downloaded = fetch_url("https://www.example.org")
text = html2txt(downloaded)

baseline()

A faster alternative that targets text paragraphs and JSON-LD metadata. Returns a tuple of (body_element, text_string, text_length).
from trafilatura import baseline, fetch_url

downloaded = fetch_url("https://www.example.org/article")
postbody, text, length = baseline(downloaded)

print(f"Extracted {length} characters")
print(text)

Output Format Selection

Set the output_format parameter on extract() to control output structure. Valid values are "txt" (default), "markdown", "json", "csv", "html", "xml", and "xmltei".
# plain text (default)
extract(downloaded)

# Markdown with formatting preserved
extract(downloaded, output_format="markdown")

# JSON with metadata
extract(downloaded, output_format="json", with_metadata=True)

# CSV
extract(downloaded, output_format="csv")

# HTML (v1.11+)
extract(downloaded, output_format="html")

# XML with structure
extract(downloaded, output_format="xml")

# TEI-XML (Text Encoding Initiative)
extract(downloaded, output_format="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

# comments are included by default — disable them
result = extract(downloaded, include_comments=False)

# tables are included by default — disable them
result = extract(downloaded, include_tables=False)

Structural Elements

# preserve bold, italic, and other inline formatting
result = extract(downloaded, include_formatting=True)

# keep link targets (href values), converting relative to absolute when url is provided
result = extract(downloaded, output_format="xml", include_links=True, url=url)

# include image alt text, src, and title attributes
result = extract(downloaded, output_format="xml", include_images=True)
Including extra structural elements works best with XML-based output formats or bare_extraction(). Certain elements may not appear in TXT or CSV output if the format does not support them.
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 using favor_precision or favor_recall.
# fewer results, less noise
result = extract(downloaded, url=url, favor_precision=True)

# more content captured, possibly more noise
result = extract(downloaded, url=url, favor_recall=True)
  • Precision: use when output contains too much noise. You can additionally pass prune_xpath to 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 the trafilatura[all] extra and the py3langid package.
# only return result if document language is German
result = extract(downloaded, url=url, target_language="de")
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.
# skip fallback detection
result = extract(downloaded, fast=True)

# combine with other options for maximum speed
result = extract(downloaded, include_comments=False, include_tables=False, fast=True)

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.
from trafilatura.settings import Extractor
from trafilatura import extract

# create a reusable configuration object
options = Extractor(output_format="json", with_metadata=True)

# adjust individual settings after creation
options.formatting = True   # same as include_formatting=True
options.source = "My Source"  # useful for debugging and provenance

# pass to extract()
result = extract(my_doc, options=options)
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

# include metadata fields in output
result = extract(downloaded, url=url, with_metadata=True)

# discard documents missing title, URL, or date
result = extract(downloaded, url=url, only_with_metadata=True)
When using "txt" or "markdown" format with with_metadata=True, a YAML front-matter header is prepended to the output:
---
title: Example Article Title
author: Jane Doe
url: https://www.example.org/article
date: 2024-02-01
---
The main article text begins here...

Date Extraction Params

Dates are extracted via the external htmldate library. You can pass custom parameters using the date_extraction_params dictionary:
result = extract(
    downloaded,
    output_format="xml",
    date_extraction_params={
        "extensive_search": True,   # broader heuristics, higher recall
        "original_date": True,      # look for the original publication date
        "outputformat": "%Y-%m-%d", # custom date format string
        "max_date": "2024-01-01",   # discard dates after this cutoff (YYYY-MM-DD)
    }
)

Memory Management

Trafilatura uses LRU caches internally to speed up repeated operations. In long-running or large-scale applications these caches may grow large. Call reset_caches() periodically to release memory.
from trafilatura.meta import reset_caches

# call at any point to clear all internal caches and run garbage collection
reset_caches()

Input Types

Raw HTML Strings

from trafilatura import extract

html = "<html><body><article><p>Hello world.</p></article></body></html>"
result = extract(html)
# → 'Hello world.'

LXML Element Trees

Pass a pre-parsed lxml.html element directly:
from lxml import html as lxml_html
from trafilatura import extract

my_doc = "<html><body><article><p>Here is the main text.</p></article></body></html>"
mytree = lxml_html.fromstring(my_doc)

result = extract(mytree)
# → 'Here is the main text.'

BeautifulSoup Objects

Convert a BeautifulSoup tree to LXML format before passing it to Trafilatura:
from bs4 import BeautifulSoup
from lxml.html.soupparser import convert_tree
from trafilatura import extract

soup = BeautifulSoup(
    "<html><body><article><p>Article content here.</p></article></body></html>",
    "lxml"
)
lxml_tree = convert_tree(soup)[0]
result = extract(lxml_tree)

Response Objects

Use fetch_response() to capture the final redirect URL and pass it directly:
from trafilatura import fetch_response, bare_extraction

response = fetch_response("https://www.example.org")

# response.url gives the final URL after any redirects
result = bare_extraction(response.data, url=response.url)

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.
from trafilatura.readability_lxml import is_probably_readerable
from trafilatura import fetch_url

downloaded = fetch_url("https://www.example.org/article")

if is_probably_readerable(downloaded):
    result = extract(downloaded)
Accepts either a raw HTML string or a pre-parsed LXML element tree.

Deprecations

The following functions and parameters are deprecated and should not be used in new code:
DeprecatedReplacement
process_record()extract()
csv_output, json_output, tei_output, xml_output paramsoutput_format parameter
bare_extraction(as_dict=True)bare_extraction().as_dict()
no_fallback parameterfast=True
max_tree_size parametersettings.cfg config file
fetch_url() decode argumentfetch_response()
decode_response() in utilsdecode_file()
with_metadata (old meaning)only_with_metadata (only docs with required metadata)

Build docs developers (and LLMs) love