How to turn a web page into Markdown in Python

Checked on 2026-11-19.

To hand a web page to a language model you want its text as Markdown: headings, lists and links kept, scripts, styles and menus gone. In Python, html2text and markdownify convert whatever HTML you give them, and trafilatura first works out which part of the page is the content. None of them runs JavaScript, and neither does the API at the end of this page.

1. html2text: convert the whole page

The oldest of the three. Its README describes "a Python script that converts a page of HTML into clean, easy-to-read plain ASCII text", which is also valid Markdown.

Python
# pip install html2text requests
import html2text
import requests

page = requests.get("https://docs.apify.com/academy", timeout=30).text

converter = html2text.HTML2Text()
converter.body_width = 0        # 0 for no wrapping; the default wraps lines at 78 characters
converter.ignore_images = True
print(converter.handle(page))

Options are attributes of the converter. Its configuration wraps lines at 78 characters unless you set body_width to 0, and ignore_links drops link addresses when you only want the words. The code is distributed under the GPLv3, which matters if you ship it inside a product.

2. markdownify: convert, and choose the tags

markdownify is built on Beautiful Soup and MIT-licensed. Its options decide what the Markdown looks like: heading_style (the default underlines headings; ATX writes them with #), and strip or convert to drop or keep tags by name.

Python
# pip install markdownify requests
import requests
from bs4 import BeautifulSoup
from markdownify import MarkdownConverter, markdownify as md

page = requests.get("https://docs.apify.com/academy", timeout=30).text

# the whole page, with # headings and without image tags
print(md(page, heading_style="ATX", strip=["img"]))

# or only the part you choose
soup = BeautifulSoup(page, "html.parser")
main = soup.find("main") or soup.find("article") or soup.body
print(MarkdownConverter(heading_style="ATX", strip=["img"]).convert_soup(main))

The second half of the sample is the useful trick: since it converts Beautiful Soup objects, you can pick the element that holds the content and convert only that.

Where both stop: they are converters. Scripts and styles are left out, but the navigation, the cookie notice, the sidebar and the footer are HTML like everything else and come out as Markdown too. On a page with a large menu, that can be most of what the model reads. Picking main or article helps on sites that use those elements and does nothing on sites that do not.

3. trafilatura: find the content first

trafilatura is an extractor. Its README says it "focuses on the actual content" and "avoids noise caused by recurring elements (headers, footers, boilerplate)", using its own rules with jusText and readability-lxml as fallbacks. Markdown is one of its output formats.

Python
# pip install trafilatura
from trafilatura import fetch_url, extract

downloaded = fetch_url("https://docs.apify.com/academy")
markdown = extract(downloaded, output_format="markdown", include_links=True)
print(markdown)   # None when no main text was found

include_links=True keeps the links inside the extracted text, with_metadata=True adds the title and other metadata, and favor_precision=True or favor_recall=True move the balance between less noise and more text. It is distributed under the Apache 2.0 license (versions before 1.8.0 were GPLv3+).

Where it stops: its documentation says it "is geared towards article pages, blog posts, and main text content. Results vary on link lists, galleries, or catalogs." An extractor decides what counts as content, so on an unusual page it can cut a part you wanted or keep one you did not. Look at the output for the kind of page you have before trusting it on thousands.

Pages built in the browser

All three work on the HTML a server sends. A page that builds its text with JavaScript sends almost none, and the result is next to nothing. trafilatura's troubleshooting page gives the fix: render the page with a browser automation library and pass the resulting HTML to extract(). Its example uses Playwright:

Python
# pip install playwright trafilatura
# playwright install
from playwright.sync_api import sync_playwright
from trafilatura import extract

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto("https://example.org")
    rendered = page.content()
    browser.close()

print(extract(rendered, output_format="markdown"))

playwright install downloads the browsers Playwright drives. A browser for each page is slower and takes far more memory than a request, so use it for the pages that need it, not for all of them.

4. An HTTP API, when you would rather not run the pipeline

The Pipefetch page content endpoint fetches one page and returns its content as Markdown, or as text with format=text.

Python
import os
import requests

res = requests.get(
    "https://pipefetch.com/v1/web/content",
    params={"url": "https://docs.apify.com/academy", "format": "markdown"},   # or "text"
    headers={"x-api-key": os.environ["PIPEFETCH_API_KEY"]},
    timeout=90,
)
if res.status_code == 404:
    # not_allowed, needs_javascript, no_content, page_not_found, website_blocked
    # or website_unreachable: not charged
    print(res.json()["error"]["code"])
else:
    res.raise_for_status()
    page = res.json()["data"]
    print(page["title"], page["wordCount"], "words,", page["tokenCount"], "tokens (estimate)")
    if page["needsJavaScript"]:
        print("This page builds its text in the browser: the content is only what its HTML holds")
    print(page["content"])

Headings, lists, quotes, tables, code blocks and links are kept. Scripts, styles, forms, buttons and images are dropped, and so are menus: blocks made almost entirely of links, and the short link fragments above the first heading and below the last. Next to content you get the page's title, description, language and canonicalUrl, its headings as an outline, a wordCount and a tokenCount. The reference lists every field.

Where it stops:

  • It does not run JavaScript either. A page built in the browser comes back with needsJavaScript true and the little text its HTML holds, or answers 404 needs_javascript when it holds none. For those pages the Playwright route above is the one that works.
  • Menus are judged from the one page alone, so a stray label or a line of footer text can remain. In our saved answer for the page in the sample, a stray "Copy for LLM" label survived.
  • tokenCount is an estimate made from the words and punctuation, not the count of a particular tokenizer.
  • One request reads one page. Links are not followed, images are not part of the Markdown, and files such as PDFs are not read.
  • robots.txt is respected: a page it closes to crawlers answers 404 not_allowed.

A request costs 1 credit and most take 2 to 9 seconds. Every 404 above is free, and so are page_not_found, no_content, website_blocked and website_unreachable. A new account has 100 free credits and needs no card. It is not an official API of the websites it reads, and Pipefetch is not affiliated with them.

Which one should you use?

SituationUse
You already have clean HTML, or you choose the element yourselfmarkdownify, or html2text
Articles, documentation and blog posts from many different sitestrafilatura
Pages that build their text in the browserPlaywright, then any of the three
An AI agent or a server where you do not want to install and maintain the librariesAn HTTP API such as Pipefetch

If trafilatura's output is good for your pages and your code already runs in Python, there is little reason to pay for an API.

robots.txt and whose text it is

The libraries fetch whatever address you give them. Whether a site's robots.txt allows it is for you to check, and Python's standard library can, as trafilatura's documentation shows:

Python
import urllib.robotparser

rules = urllib.robotparser.RobotFileParser()
rules.set_url("https://docs.apify.com/robots.txt")
rules.read()
print(rules.can_fetch("*", "https://docs.apify.com/academy"))   # True or False

Converting a page to Markdown does not change whose text it is: the rights stay with whoever published it. That holds for every route here.

Try it with 100 free credits. No card needed. No scraper to build or maintain. Get an API key or read the docs.

Free tools for this

Every source

YouTube

Instagram

TikTok

Facebook

Google

Threads

LinkedIn

App stores

Steam

X

Pinterest

Airbnb

Real estate

Keywords

Job boards

Eventbrite

Shopify stores

Public tenders

All guides