Blog / AI agents

Website to Markdown: Clean Page Text for LLMs

To turn a website into markdown, fetch the page and convert its HTML, keeping headings, links, lists and code and dropping scripts, styles and navigation. You can do it in one call with the scrape endpoint and response_type=markdown, at 1 credit a page, or in Python with requests, BeautifulSoup and markdownify. Either way, check first whether the site already publishes a markdown copy, and trim the result before it goes into a model's context.

Why convert a website to markdown for an LLM?

Markdown keeps the structure a model uses to read a page, headings, lists, links, tables and code, and drops the markup it doesn't need. Raw HTML spends most of its length on tags, attributes, inline scripts and styles. Plain text goes too far the other way: it loses which line is a heading and where a link pointed.

The difference is large. On the PyPI page for markdownify, fetched on 25 October 2026, the HTML was 144,674 characters. Converting the whole document gave 35,584 characters of markdown, about a quarter of the size. Converting only the main content, with navigation and footers removed first, gave 22,223. A model's context window is billed and limited by tokens, so that cut goes straight to cost and to how many pages fit in one prompt.

Markdown is also what most retrieval pipelines chunk on: split at ## headings and each chunk keeps its own topic. RAG with Live Web Data covers when you need chunking at all.

Does the site already publish markdown?

Check this first, because it's free and exact. The llms.txt proposal asks sites to put a markdown file at /llms.txt that summarises the site and links to its key pages, and to serve a clean markdown copy of pages at the same URL with .md appended (llmstxt.org, 2024). Documentation sites built with some generators do this by default.

So before converting https://example.com/docs/setup, try https://example.com/docs/setup.md and https://example.com/llms.txt. If either exists, it was written for exactly this job, by the people who know which parts of the page matter. It's still a proposal rather than a formal standard, so most sites don't have it, and you'll need one of the two methods below.

How do you get a page as markdown with one API call?

The scrape endpoint fetches a URL and returns it in the format you ask for, so the fetching and the conversion happen in one request and you don't run a parser. Pass the page in url, URL-encoded, and set response_type=markdown. The other two parameters are optional:

curl "https://api.perceptlayer.com/v1/web-scraper/scrape?url=https%3A%2F%2Fexample.com&response_type=markdown" \
  -H "X-API-Key: $API_KEY"

We didn't run this request for this post, and we haven't recorded a response from this endpoint, so we can't show its output here. Run it in the playground on the Scrape endpoint page with your own URL to see exactly what comes back before you build on it.

Parameter Type Required Notes
url string Yes The page to fetch, up to 2048 characters
response_type string No json or markdown
javascript boolean No Render the page's JavaScript; see the Web Scraper API page
include_html boolean No Include the page's HTML as well; see the endpoint page

Send the key in the X-API-Key header; keys start with sk_live_. The authentication docs cover the alternatives. For pages that build their content in the browser, a plain fetch gets an empty shell, which is what the javascript parameter is for.

What does it cost per page?

Each successful call costs 1 credit, so a page costs 1 credit whether it converts to 2,000 characters or 200,000. A failed call costs nothing and returns X-Credits-Used: 0; every successful response reports X-Credits-Used and X-Credits-Remaining.

Some arithmetic: an agent that reads 30 pages a day uses 30 × 30 = 900 credits a month. The 100 free credits you get once, after verifying an email address, cover its first 3 days, and the Starter pack's 10,000 covers 11 months. A documentation crawl of 20,000 pages is 20,000 × 1 credit = 20,000 credits, inside the Build pack's 50,000. See pricing for what credits cost.

How do you convert HTML to markdown yourself in Python?

Fetch the HTML, cut it down to the main content, then convert. The library doing the conversion is markdownify, which turns HTML into markdown and takes options for heading style and for tags to strip or keep (markdownify on PyPI, 2026). BeautifulSoup does the cutting. Install both with pip install requests beautifulsoup4 markdownify.

import re
import sys

import requests
from bs4 import BeautifulSoup
from markdownify import markdownify

STRIP = ["script", "style", "noscript", "svg", "iframe", "form", "nav", "header", "footer", "aside"]


def page_to_markdown(url):
    html = requests.get(url, headers={"User-Agent": "md-fetch/1.0"}, timeout=30).text
    soup = BeautifulSoup(html, "html.parser")
    main = soup.find("main") or soup.find("article") or soup.body or soup
    for tag in main.find_all(STRIP):
        tag.decompose()
    md = markdownify(str(main), heading_style="ATX", strip=["img"])
    md = re.sub(r"\n{3,}", "\n\n", md).strip()
    return html, md


if __name__ == "__main__":
    url = sys.argv[1]
    html, md = page_to_markdown(url)
    naive = markdownify(html, heading_style="ATX")
    print(f"html chars: {len(html):,}")
    print(f"naive markdown chars: {len(naive):,}")
    print(f"cleaned markdown chars: {len(md):,}")
    print(md[:600])

We ran this with Python 3, markdownify 1.2.3 and BeautifulSoup 4.15.0 against https://pypi.org/project/markdownify/. The output began:

html chars: 144,674
naive markdown chars: 35,584
cleaned markdown chars: 22,223
# markdownify 1.2.3

Convert HTML to markdown.

pip install markdownify
…

heading_style="ATX" writes headings as # lines rather than underlines, which is what most chunkers split on. Prefer <main> or <article> when the page has one: it's the cheapest way to drop everything around the content.

When is the do-it-yourself route enough?

It's enough when the pages are static HTML, you fetch a modest number of them, and the sites allow it. It costs nothing per page and you control every rule. It stops being enough when pages render in the browser (a plain requests.get returns a near-empty shell), when you need many sites with different layouts, or when you'd rather not maintain fetching code. That trade-off is the subject of Scraper or API: What Maintaining a Scraper Really Involves.

Either way, read the site's terms and robots.txt before you fetch it (RFC 9309, 2022), keep your request rate low, and don't fetch pages behind a login.

What should you strip before the markdown reaches a model?

Strip anything that isn't the page's content, because it costs tokens on every call and can mislead the model into quoting a menu or a cookie notice. The conversion step handles markup; this step handles content that is valid markdown but useless to a model answering a question about the page.

  1. Navigation, headers and footers. Menus and link lists repeat on every page of a site. Remove nav, header, footer and aside before converting, as the script does.
  2. Scripts, styles, SVG and forms. They convert to noise or to nothing useful.
  3. Images. An image becomes a markdown image tag with its alt text and URL; unless the model needs the alt text, drop it with strip=["img"].
  4. Cookie banners and newsletter boxes. They're often plain divs; remove them by a class or id you see on the site.
  5. Long link URLs. Tracking parameters make links long. If the model only needs the anchor text, convert links with strip=["a"].
  6. Repeated blank lines. Collapse three or more newlines to two.

Then cap the length. If a page is still too long, keep the first sections or split at ## headings and send only the chunks that match the question. Trim API Responses for LLM Context shows the same idea applied to JSON responses.

How does this fit an agent that reads web pages?

An agent needs one tool that takes a URL and returns markdown. You can wrap the Python function above as that tool, or give the agent the scrape endpoint through the MCP server at https://perceptlayer.com/mcp. With MCP the agent calls call_endpoint with the endpoint ID web-scraper.scrape and {"url": "…", "response_type": "markdown"}; the result reports the credits used and remaining.

Before scraping, the agent should check whether a structured endpoint covers the site: the catalogue has 707 websites and 3,834 endpoints, and a search result or a product listing comes back as named JSON fields, which beat markdown for values like prices and ratings. MCP Server for Web Scraping walks through that search-then-scrape order, and the AI agents docs cover setup.

Try it on a page you care about: run the scrape endpoint in the playground on the Web Scraper API page, or get a free API key and send the cURL request above.

APIs in this post

Frequently asked questions

How much does converting a website to markdown cost?

With the scrape endpoint, each successful page costs 1 credit, whatever its length, and a failed call costs nothing. Every account gets 100 free credits after verifying an email address, enough for 100 pages. Converting with your own Python code costs nothing per page, but you run and maintain the fetching yourself. See pricing for credit packs.

Can I convert a whole website, not just one page?

Yes, one page at a time. Start from the site's sitemap or its /llms.txt if it has one, collect the URLs you need, and convert each. With the scrape endpoint that's one call and 1 credit per URL. Respect the site's robots.txt and terms, and pace requests; the rate limits docs give the per-account limits.

Why does my converted markdown come out empty?

The page probably builds its content with JavaScript, so the HTML you fetched is a shell with no text in it. A plain HTTP fetch can't run scripts. Use a browser automation tool, or call the scrape endpoint with javascript=true so the page is rendered before conversion.

Is markdown better than plain text for RAG?

Usually. Markdown keeps headings, so you can split a page into chunks that each cover one topic, and it keeps links and tables, which plain text flattens. Plain text is slightly shorter. If your pipeline never uses structure, plain text works; if it chunks or cites sources, markdown is the better input.

What happens if the URL fails to load?

You get an HTTP status and a JSON error body with a code, a message and a request_id, and you aren't charged. A source_error (502) means the source didn't return the page; invalid_parameters (422) usually means the url is malformed or too long. The errors docs list every code.

  1. CrewAI Tools: Build a Custom Tool for Live Web Data

    Build a CrewAI custom tool (a BaseTool subclass) that searches Google for live results, cap it at 5 calls a run, or load MCP tools instead. Tested code.

  2. Build a Market Research Agent with Search and Trends Data

    Wire Google Search, Trends and News into one Python agent, cap it at 8 credits per question, and see a recorded Trends response.

  3. Track Brand Mentions in AI Answers with an API

    A daily Python job that sends fixed prompts to an LLM answers endpoint and Google's AI overview, logs brand mentions and cited domains, at 2 credits per prompt.

Start with 100 free credits

No password to set. We email you a sign-in link, and your key works on every API.

No credit card. 100 free credits on signup.