To extract code blocks from web pages, start with the source HTML and read each block inside the page's main document. Take the code text in order without trimming its line starts or inserting spaces between syntax-highlighted tokens. Save the block's location alongside its text so you can find the same example again. If you use a Markdown converter, parse its fences and compare each code body against the source before indexing or copying it. When a snippet appears only in the rendered page, inspect that DOM and run the same checks there.

Find the boundary of the snippet

Start with main pre code on a page that uses semantic markup for examples. If a known documentation template puts the text directly under <pre>, select that block. A page may also use <pre> for sample output, ASCII diagrams, or logs. Decide which of those belong in your collection. Inline <code> in a paragraph usually names a command, variable, or argument and belongs with the sentence that explains it.

A highlighter can wrap keywords, quotes, and operators in separate spans. Joining the spans with a space changes the text if a string literal or operator spans multiple nodes. Trimming individual nodes can eat a leading indent or the spaces between tokens. Beautiful Soup's text extraction options let you keep the original order with an empty separator and stripping turned off.

Treat line numbers and copy-button labels as a selection problem. Pygments' HTML formatter can put its line numbers in a separate table cell or inside the code's <pre>. Inspect the actual markup and exclude a known decoration by its element or class. A rule that removes digits from every line can damage numeric data or commands. Some templates rely on <br> or line wrappers instead of text newlines. Give those templates their own tested line-joining rule.

Compare a real page with its converted Markdown

Save the same public documentation page twice. Take the HTML directly and get the cleaned Markdown from the preview's JSON response. The target is the AnyCrawler Fetch documentation, which shows when to choose an HTML-first request or render a page whose content depends on JavaScript. The free URL-to-Markdown tool can repeat the Markdown preview in a browser. It reads one URL per request and can serve cached content.

curl -fsSL --max-redirs 3 --max-time 30 \
  https://anycrawler.com/crawler/page/fetch/ -o page.html

curl -fsSG --max-time 30 \
  --data-urlencode 'url=https://anycrawler.com/crawler/page/fetch/' \
  https://api.anycrawler.com/free/v1/crawl -o free.json

The check below uses beautifulsoup4 and markdown-it-py. This fixture has a <main> and uses <pre> for its examples. Select a narrower document region on a template with other preformatted content. The code assumes both views show the same page version and retain the same order. Confirm that assumption before using positional pairing on other pages.

import json
from pathlib import Path

from bs4 import BeautifulSoup
from markdown_it import MarkdownIt

html = BeautifulSoup(Path("page.html").read_bytes(), "html.parser")
document = html.select_one("main")
if document is None:
    raise ValueError("Expected the documentation page to have a main element")

source_blocks = []
for pre in document.select("pre"):
    code = pre.select_one("code") or pre
    source_blocks.append(code.get_text(separator="", strip=False))

free = json.loads(Path("free.json").read_text(encoding="utf-8"))
if free.get("ok") is not True or free.get("status_code") != 200:
    raise ValueError("The preview did not return the expected page")

tokens = MarkdownIt("commonmark").parse(free["results"]["markdown"])
fences = [token for token in tokens if token.type == "fence"]
if not source_blocks or len(source_blocks) != len(fences):
    raise ValueError("Review missing, extra, or differently formatted blocks")

for position, (source, fence) in enumerate(zip(source_blocks, fences), 1):
    expected = source if source.endswith("\n") else source + "\n"
    if fence.content != expected:
        raise ValueError(f"Code differs at block {position}")
    print(f"Block {position} matches with the fence line ending")

Both requests returned HTTP 200 on the sample. The parser found three source blocks and three Markdown fences in matching order. The converted bodies kept the spaces and line breaks in the source and added a final newline to each block. The fences had no language labels. The Free response supplied the requested URL and upstream status but omitted the final target URL and credits used. The direct GET independently confirmed the effective URL of the HTML sample.

This check deliberately accepts the newline needed before a Markdown closing fence. Keep the original code text separately for byte-sensitive uses. When emitting your own Markdown, start the fence at the left margin and choose a delimiter that survives the snippet's literal contents. CommonMark's fence rules explain how an indented opening fence can remove spaces from the code body and how a matching delimiter closes it.

Decide which failures need a new capture

What you see Likely place to check What to do
The page has inline code and no block Element selection Keep short identifiers with their paragraph.
Expected code appears only in the live DOM Page acquisition Render the public page, then inspect the example's container.
Copy text or line numbers enter the body Template markup Exclude the verified decoration and compare a fresh sample.
The block exists in HTML but its fence is missing Conversion or page version Check source identity, then extract the block directly if the converter omitted it.
Text differs after the allowed final newline Conversion or pairing Check exact line starts and section identity. Hold the converted snippet until the difference is explained.

Use Search to discover a documentation URL if you do not have one. Fetch or Render can acquire a known page, and a screenshot can help a reviewer locate a visually unusual snippet. For source comparison, save the extracted text with the effective source URL, a verified heading anchor when available, and the block's position within that section. If viewing the example requires clicking a language tab or loading a collapsed section, interactive browser automation belongs in a separate workflow. Record which state supplied the code.

When a documentation excerpt stops being enough

A code block can be faithful to the page and still be unsuitable as an executable file. Documentation may omit imports or show only the lines that change. A retrieval system can link someone to the exact heading and preserve that excerpt. A build or automated check may instead need the project's versioned source file. If your system accepts both, record the page location and the file revision separately so reviewers can tell which artifact was checked.

Frequently asked questions

Can I select every code element on a page?

Use a block selector if you want complete examples. An inline code element can hold an option name or a tiny expression and lose its meaning when you remove it from its sentence. A known template may use a pre element without a code child, so inspect the HTML before adding a fallback. Limit the search to the document area that contains the examples.

Why did my extracted Python code lose indentation?

Check the places where your script turns markup into text. A call that strips each text node or collapses runs of whitespace can move statements out of their blocks. An indented Markdown fence can also remove leading spaces during parsing. Compare the source and converted bodies line by line. Preserve the exact leading whitespace where the source contains it.

How should I remove line numbers from extracted code?

Find the markup that produces the line numbers. A dedicated gutter cell or a known number span gives you an element you can exclude while keeping the source text. Avoid guessing from a line's initial digits. Those digits might be part of the example itself. Retest the selector after a documentation theme change, since the layout can move the line numbers.

What if the example appears only after JavaScript runs?

Inspect the initial HTML and the rendered page for the specific block. If it appears in the rendered DOM, collect from that state and verify the same text and position checks. Some examples appear only after choosing a tab or expanding a section. If you use interactive automation for that, save the selected state so another run can reproduce your result.

When can I keep code from a Markdown converter?

Keep a converted snippet when you can tie it to the same source block and explain every allowed change, such as the terminal line feed used by the fence. Use a Markdown parser to read the body and compare its characters. If a count, section location, or code line differs, resolve the mismatch before publishing or indexing that copy. Keep a verified raw excerpt for workflows that need exact source text.