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.
# 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.
# 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.
# 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 foundinclude_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:
# 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.
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
needsJavaScripttrue and the little text its HTML holds, or answers 404needs_javascriptwhen 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.
tokenCountis 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.txtis respected: a page it closes to crawlers answers 404not_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?
| Situation | Use |
|---|---|
| You already have clean HTML, or you choose the element yourself | markdownify, or html2text |
| Articles, documentation and blog posts from many different sites | trafilatura |
| Pages that build their text in the browser | Playwright, then any of the three |
| An AI agent or a server where you do not want to install and maintain the libraries | An 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:
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 FalseConverting 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
- HTML to Markdown converter
- cURL to Python converter
- robots.txt tester
- Meta title and description length checker
APIs used in this guide
More Websites guides
- Clearbit Logo API alternatives: get a company logo from its domain
- How to extract email addresses from a website in Python
- How to detect what a website is built with, in Python
- How to get the contact emails and phone numbers of websites in Google Sheets
- How to build a LangChain tool that reads web pages and searches Google
- How to turn a web page into Markdown in JavaScript for RAG
- How to extract social media links from a website in Python
- How to get a website's favicon in Python
- How to check robots.txt in Python before you fetch a page
Guides for other sources
Every source
YouTube
- How to get a YouTube transcript in Python
- How to get a YouTube transcript in Node.js
- YouTube API quota exceeded: what the error means and how to fix it
- How to find a YouTube channel ID from a handle or URL
- How to download YouTube subtitles as SRT or VTT
- youtube-transcript-api RequestBlocked or IpBlocked: why it happens and how to fix it
- How to get YouTube comments in Python
- How to search YouTube from Python
- How to list a YouTube channel's videos in Python
- How to summarize a YouTube video with an LLM in Python
- How to get YouTube transcripts and video stats in Google Sheets
- How to get YouTube video views and likes in Python
- How to get YouTube transcripts in n8n, Make and Zapier
- LangChain YoutubeLoader fails on a server: why, and a loader that works
- How to get a YouTube channel's subscriber count in Python
- How to give Claude or Cursor access to YouTube (MCP server)
- How to get YouTube comments in Node.js
- How to analyze YouTube comments with an LLM in Python
- How to list a YouTube channel's Shorts in Python
- How to search YouTube from JavaScript
- How to get an Instagram follower count in Python
- Instagram Basic Display API alternatives: what to use after the shutdown
- Instaloader 401 Unauthorized, 429 and "Login required": what to do
- How to calculate an Instagram engagement rate in Python
- How to get an Instagram follower count in Node.js
- How to get Instagram follower counts in Google Sheets
- How to get Instagram Reel views in Python
TikTok
- How to get a TikTok video's views and likes in Python
- How to get the comments of a TikTok video in Python
- How to get a TikTok follower count in Python
- TikTok Research API: who can get access, and what to do if you cannot
- How to get TikTok video views, likes and shares in Node.js
- How to get TikTok views, likes and follower counts in Google Sheets
- How to get a Facebook Page's posts without app review
- Is there a Facebook Marketplace API?
- Facebook Groups API alternatives after its removal in 2024
- How to get a Facebook Page's follower count and contact details in Python
- How to get Google search results in Python
- pytrends 429 TooManyRequestsError: what it means and what to do
- How to get Google Trends data in Python
- Why is Wyoming first in Google Trends?
- How to get Google search results in Node.js
- How to get Google search results into Google Sheets
- How to give an LLM live Google results with tool calling
Threads
- How to get LinkedIn company data in Python
- How to search LinkedIn jobs from Python
- How to get a LinkedIn company page's latest posts in Python