Webpage conversion guide

How to Convert a Webpage to Clean Markdown

Create compact, readable Markdown from a public webpage while preserving the structure people and downstream systems need.

Laptop and notes used while converting webpage content to Markdown
Photo by Ron Lach on Pexels.

A useful webpage-to-Markdown workflow does not translate every HTML tag mechanically. It isolates meaningful content first, then converts semantic structure into a stable format that is easy to read, diff, search, and send to language models.

Compare clean Markdown with plain text using ToolTrace's free Web Page Scraper.

Decide what the Markdown must preserve

Markdown is effective for documentation, knowledge bases, migration, search, and RAG because it keeps hierarchy without browser styling. It is not a replacement for HTML when layout, forms, or interactive behavior matter.

Choose between the complete page and readable main content. Most content workflows need the latter.

Think about who reads the output. An Obsidian vault wants headings and inline links intact. A RAG pipeline wants plain prose with stable section boundaries so chunking does not slice through a code block. A migration from WordPress to a static site needs tables and image references preserved. Each job has a different definition of clean.

Write the required fields before picking a converter. Title, canonical URL, main body, and section hierarchy cover most work. Author, date, and tags matter for migration and feeds. If a field is not in your contract, delete it from the output rather than preserving noise someone has to filter later.

Fetch and validate the source

Follow redirects, record the final URL, restrict protocols and content types, and set response limits. Verify that the response contains expected content rather than an access or consent screen.

Reject responses that do not advertise HTML. A PDF or JSON endpoint has no useful tag mapping, and feeding it to a converter wastes a request. A 200 behind a cookie wall also counts as a failure for this purpose, so check for the expected H1 or a known block before trusting the body.

Keep the final URL. Relative links, image sources, and anchor fragments resolve against it, and a page served from /blog/post/ behaves differently from the same post served from the site root. Use browser rendering only when JavaScript creates essential text. Static HTML is the faster default.

Remove page chrome before conversion

Discard scripts, styles, navigation, repeated headers and footers, ads, cookie controls, and unrelated recommendations before mapping tags. Otherwise valid Markdown remains semantically noisy.

The cleanup selector list is almost always the same: nav, header, footer, aside, script, style, noscript, form, iframe, and anything flagged as advertising or related content. Many sites also label newsletter prompts and author boxes with distinctive class names you can remove without harming the article body.

Err on the side of removing too much. A missing newsletter box costs nothing. A retained one adds "Sign up for our newsletter" to every chunk in the RAG index. For article pages, follow the main article extraction workflow.

Map semantic HTML deliberately

Convert headings by document hierarchy, paragraphs to separated blocks, lists to list syntax, links to descriptive Markdown links, and code to inline or fenced code. Preserve block quotes and meaningful tables.

Headings carry meaning that Markdown preserves cheaply, so get the hierarchy right. An H2 that was styled to look like an H1 should still convert as H2. Rewriting rank by visual weight breaks table-of-contents generation and section-level retrieval downstream.

Code blocks are where converters most often fail. Tabs become spaces, leading whitespace collapses, and language hints disappear. Pick a converter that keeps the language class when present and leaves raw whitespace inside fences alone. Do not infer heading rank from font size and do not normalize whitespace inside code examples.

When static HTML is not enough

Not every page serves what you see. Single-page apps built with React, Vue, or Svelte often ship an empty <div id="app"></div> and populate it from JavaScript after load. A static fetch returns the shell, and any converter gives you nothing.

Three signals say you need a browser. The response body is small but the rendered page shows thousands of words. The initial HTML contains a loading spinner or skeleton markup. Important text only appears in the DOM after XHR requests finish.

When you reach that point, the options are Playwright, Puppeteer, or a scraping API that renders for you. Each adds latency and cost, so default to static fetching and switch only when the signals above show up. See static versus browser-rendered scraping for the full decision tree, and consider the Content Extraction API when you need rendering without running the browser yourself.

Validate Markdown quality in production

Check heading order, list indentation, closed code fences, resolved links, and source coverage. Sanitize retained HTML before rendering it in a browser.

Build a small fixture set of ten to twenty pages across the templates you care about and store the expected Markdown for each. Any converter change runs against the set, and a diff review is quicker than noticing a regression in production a week later.

Monitor the output in aggregate too. Watch average word count, link count, and heading count by domain. A sudden drop usually means the publisher redesigned and the selector that removed their navigation now removes the article. Version the converter, cache unchanged pages with content hashes, and test representative templates.

Convert HTML to Markdown in Python

Three libraries cover most webpage-to-Markdown work, and the right choice depends on how much layout the input still contains.

markdownify converts whatever HTML you hand it, so the quality depends entirely on removing navigation and footers first.

import requests
from bs4 import BeautifulSoup
from markdownify import markdownify

html = requests.get("https://example.com/article", timeout=20).text
soup = BeautifulSoup(html, "lxml")

for tag in soup.select("nav, header, footer, aside, script, style"):
    tag.decompose()

main = soup.select_one("article, main") or soup.body
markdown = markdownify(str(main), heading_style="ATX")

trafilatura identifies the main content itself, which is usually the better default for pages you have not seen.

import trafilatura

downloaded = trafilatura.fetch_url("https://example.com/article")
markdown = trafilatura.extract(downloaded, output_format="markdown")

html2text with readability-lxml is the older combination, and it still wins for one specific job: producing wrapped text with reference-style links that some note-taking apps render better than inline links.

import requests
from readability import Document
import html2text

response = requests.get("https://example.com/article", timeout=20)
doc = Document(response.text)

converter = html2text.HTML2Text()
converter.body_width = 0
converter.ignore_images = False
markdown = converter.handle(doc.summary())
title = doc.title()

When each one wins. Reach for trafilatura when the input is a mixed set of articles from publishers you have not surveyed. The heuristics do more work than any manual cleanup. Reach for markdownify when you have already isolated the main content, want ATX headings, and need direct control over the tag mapping. Reach for html2text with readability when the output is going into a tool that prefers reference links, or when you want tight control over width and wrapping.

None of these run JavaScript. On a client-rendered page they all return an empty shell, which is the point at which you need a browser or an API that renders before extracting.

The free Web Page Scraper handles the rendering decision for you and returns Markdown directly.

Prepare Markdown for LLM consumption

Markdown headed for a language model has different requirements than Markdown headed for a human reader. Chunk size, metadata, and separator consistency decide retrieval quality more than the prose itself.

Pick a chunk size that matches the embedding model. Most models work well between 400 and 800 tokens per chunk with a short overlap of 50 to 100 tokens. Split on H2 and H3 boundaries where possible so a chunk never starts mid-section, and never slice inside a fenced code block.

Add YAML frontmatter with the fields the retriever needs: source URL, title, canonical URL, author, publication date, extraction time, and content hash. The retriever can then filter and cite without reparsing the body.

---
source_url: https://example.com/article
title: Example Article Title
canonical: https://example.com/article
author: Jane Doe
date: 2026-03-14
extracted_at: 2026-10-31T12:00:00Z
hash: 4f3e8a2b...
---

Keep a stable Markdown dialect. Mixing ATX and Setext headings, or switching between asterisk and dash bullets across documents, confuses chunk-boundary detectors in some frameworks. Pick one dialect and lint for it. For a complete ingestion pipeline see web scraping APIs for AI agents and RAG, and use the llms.txt Generator alongside the Article Text Extractor when the goal is making a site itself friendlier to language models.

Review a Markdown conversion example

A documentation page may contain a breadcrumb, sidebar, article heading, paragraphs, a numbered procedure, code, a comparison table, and footer navigation. A clean conversion should preserve the article hierarchy and code exactly while excluding repeated navigation. Inspect the output as a reader would, not only as valid syntax.

  • Heading levels should reflect the document hierarchy.
  • List nesting must remain unambiguous.
  • Code fences must close and preserve whitespace.
  • Relative links should resolve against the final page URL.
  • Complex tables should not be flattened into misleading rows.

For a source-text-only workflow, first isolate the article with the Article Text Extractor.

Make conversion reliable at scale

Store the requested URL, final URL, collection time, converter version, content hash, and warnings with the Markdown. Normalize predictable whitespace, but do not silently rewrite quotations, code, numbers, or link destinations.

Measure malformed output, unresolved links, empty results, conversion size, latency, and template-specific regressions. Sanitize any retained HTML before displaying it. When conversion supports a knowledge system, version documents so stale chunks can be removed rather than accumulated beside newer text.

Common failure patterns and how to diagnose them

Start with the earliest failing layer. If a request does not return the expected page, inspect DNS, redirects, HTTP status, content type, firewall behavior, and access controls before changing extraction or metadata rules. If the correct document arrives but the result is empty, compare initial HTML with the rendered page and determine whether JavaScript supplies the missing information.

When only some fields are wrong, inspect the page source and identify which signal produced each value. A stale canonical, duplicated title, malformed JSON-LD block, relative URL, or CMS fallback should be corrected at its source. Avoid adding a special case for one URL when the same template defect affects a wider section of the site.

Finally, distinguish a deterministic failure from a recommendation. Invalid JSON, an unreachable URL, or a conflicting index directive can be proven. Content usefulness, ideal wording, and business priority still require human judgment. A professional report should show the evidence, explain the consequence, and avoid presenting a heuristic as a universal rule.

Production quality checklist

Validate the exact production URL, not only a CMS preview, local fixture, or isolated code sample. Confirm the requested URL, final URL, HTTP status, content type, and visible result agree with the page you intended to process. Test at least one normal case, one sparse page, one redirected URL, and one expected failure so the interface communicates limitations clearly.

  • Keep source URLs and observation times with exported results.
  • Use descriptive labels, headings, and error messages.
  • Specify image dimensions and keep media files lightweight.
  • Test keyboard access and narrow mobile layouts.
  • Separate automatic checks from recommendations requiring judgment.
  • Respect access controls, publisher policies, privacy, and applicable law.

After deployment, rerun the workflow against representative URLs and monitor for changes in output size, missing fields, status codes, response time, and template behavior. Keep a known-good result for comparison. When a check fails, fix the source template or data pipeline rather than hiding the warning in the interface.

Frequently asked questions

Can Markdown preserve every webpage feature?

No. It preserves document structure well, but complex layout and interactivity require HTML or structured data.

Should navigation links be included?

Usually not for readable-content or RAG workflows. Include them when site discovery is the task.

Does conversion make HTML safe?

No. Sanitize retained HTML and validate URLs before displaying or processing it.

Which Python library should I use to convert HTML to Markdown?

Use trafilatura for pages you have not surveyed, markdownify when the HTML is already cleaned to the main content, and html2text with readability-lxml when you need reference-style links or controlled line wrapping.

How do I convert a JavaScript-rendered page?

Render it first with Playwright, Puppeteer, or a rendering API, then run the resulting HTML through a Markdown converter. Static fetchers see only the empty shell.

What chunk size works for RAG when the source is Markdown?

Most embedding models work well between 400 and 800 tokens per chunk with a 50 to 100 token overlap. Split on H2 or H3 boundaries so chunks start at a semantic break, and never split inside a fenced code block.