Thursday, December 3, 2026
HomeWeb developmentWhat Breaks and Easy methods to Repair It

What Breaks and Easy methods to Repair It


Run Apple’s MacBook Air web page by trafilatura, a Python library that pulls the primary textual content out of internet pages, and also you get 106 phrases again. The web page has greater than 7,000 phrases of seen textual content. For those who construct retrieval-augmented era (RAG), that hole decides what your mannequin can discover.

The crew at Apify, which makes one of many three instruments in contrast beneath, turned 20 public internet pages into Markdown 3 ways and measured what broke. The numbers on this article come from that take a look at. SitePoint’s information on constructing a fetch layer for AI brokers covers getting the web page. This text picks up the place it leaves off, on the line “extract_main_text is no matter readability or boilerplate-removal step you already use”. Here is what breaks in that step and the Python to repair every drawback.

Key Takeaways

  • Changing a complete web page to Markdown retains the menus, footers, and hyperlink lists. Within the take a look at it used 3.4 instances the tokens of a main-content extractor.
  • The extractor within the take a look at saved beneath 2% of the seen textual content on two product pages, and its recall setting did not assist.
  • Pages rendered with JavaScript can return an empty shell to a plain HTTP request. Verify the seen textual content earlier than you belief the output.
  • Verify construction too. One extractor dropped each heading on a GitHub docs web page and flattened Python code examples.
  • Take away blocks repeated throughout a website, then chunk by heading. In an additional take a look at on 4 GitHub docs pages, blocks repeated throughout pages made up 43% of the tokens (1.3% on Python docs).

The Take a look at: 20 Pages, Three Strategies

The take a look at used 4 pages every of 5 varieties: documentation (Python, MDN, FastAPI, GitHub), weblog posts, information and Wikipedia articles, product pages (Apple, a GitHub repository, Allbirds, IKEA), and pages that render with JavaScript (crates.io, Bluesky, Mastodon, a Notion assist web page).

Every web page went by three strategies on November 5, 2026:

  1. Plain conversion: requests plus markdownify on the entire HTML.
  2. Essential-content extraction: trafilatura 2.0.0 on the identical HTML.
  3. A rendering crawler: Web site Content material Crawler from Apify, which hundreds the web page in a headless browser earlier than changing it.

Tokens have been counted with tiktoken (the o200k_base encoding that GPT-4o makes use of), together with traces that appear to be boilerplate: cookie notices, “sign up”, “subscribe”, copyright traces.

  • Plain conversion: 210,158 tokens throughout the 20 pages, 3 pages beneath 100 phrases, 179 boilerplate traces, 152 Markdown desk rows, 2 pages with no headings.
  • trafilatura: 62,236 tokens, 5 pages beneath 100 phrases, 8 boilerplate traces, 10 Markdown desk rows, 8 pages with no headings.
  • Web site Content material Crawler: 106,332 tokens, 1 web page beneath 100 phrases, 12 boilerplate traces, 86 Markdown desk rows, 0 pages with no headings.

[IMAGE: Bar chart: total tokens for the same 20 pages: plain conversion 210,158, Website Content Crawler 106,332, trafilatura 62,236]

Whole tokens after changing the identical 20 pages. Take a look at run on November 5, 2026.

No technique gained on each web page. The remainder of this text goes by the failures one by one.

Drawback 1: Many of the Web page Is not Content material

The very first thing most individuals write appears to be like like this:

python

import requests
from markdownify import markdownify

HEADERS = {"Consumer-Agent": "my-rag-bot/1.0 (+https://instance.com/bot)", "Settle for": "textual content/html"}

def naive_markdown(url):
    html = requests.get(url, headers=HEADERS, timeout=30).textual content
    return markdownify(html, heading_style="ATX")

It does work, and also you get Markdown. The issue is that you simply get every thing with it: menus, footers, cookie notices, and the article someplace within the center. On the Cloudflare weblog put up within the set, the plain conversion was 19,425 tokens. The extracted article was 4,541. Throughout 20 pages, the plain output had 5,444 hyperlinks, 179 boilerplate traces, and 332 traces repeated inside the similar web page. Each a kind of results in an embedding, the place a query like “how do I sign up” can pull up a navigation chunk as an alternative of the true reply.

A main-content extractor scores every block of the web page and retains those that appear to be the physique:

python

import trafilatura

def extract_markdown(html):
    return trafilatura.extract(
        html,
        output_format="markdown",
        include_tables=True,
        include_links=True,
        include_comments=False,
    )

On articles this works effectively. Throughout all 20 pages, boilerplate traces fell from 179 to eight, and whole tokens fell by 70%. The difficulty begins on pages that are not articles.

Drawback 2: The Extractor Throws Away Pages That Aren’t Articles

Extractors like this are constructed round articles. Product pages, touchdown pages, and repository pages do not appear to be that, so the extractor retains a fraction and drops the remainder:

  • Apple MacBook Air: 7,158 seen phrases within the HTML. trafilatura saved 106, Web site Content material Crawler saved 1,513.
  • Allbirds product web page: 15,298 seen phrases within the HTML. trafilatura saved 200, Web site Content material Crawler saved 1,244.
  • IKEA BILLY bookcase: 2,395 seen phrases within the HTML. trafilatura saved 412, Web site Content material Crawler saved 3,238.

Setting trafilatura’s favor_recall=True made no actual distinction on any of the three.

The repair is to note the issue per web page. Examine what the extractor saved with how a lot textual content the web page has:

python

from bs4 import BeautifulSoup

def visible_words(html):
    soup = BeautifulSoup(html, "lxml")
    for tag in soup(["script", "style", "noscript", "template"]):
        tag.decompose()
    return len(soup.get_text(" ").cut up())

def diagnose(html, markdown):
    web page = visible_words(html)
    saved = len((markdown or "").cut up())
    if web page < 200:
        return "needs_browser"          
    if saved < 0.15 * web page:
        return "extractor_dropped_content"   
    return "okay"

For pages flagged extractor_dropped_content, fall again to changing the web page’s predominant area with the apparent noise eliminated:

python

from bs4 import BeautifulSoup
from markdownify import markdownify

NOISE = ["nav", "header", "footer", "aside", "form", "script", "style",
         "noscript", "svg", "button", "iframe", "[role=dialog]", "[aria-hidden=true]"]

def main_region_markdown(html):
    soup = BeautifulSoup(html, "lxml")
    root = soup.select_one("predominant, [role=main], article") or soup.physique
    for selector in NOISE:
        for tag in root.choose(selector):
            tag.decompose()
    return markdownify(str(root), heading_style="ATX")

Within the take a look at set, diagnose despatched Apple, Allbirds, and the Notion assist web page to the fallback, and marked the three JavaScript shells from Drawback 3 as needs_browser. The fallback introduced Apple from 106 phrases to three,845, Allbirds from 200 to 921, and Notion from 45 to 195. It is a blunter device than the extractor, so use it solely as a fallback. The 15% threshold is a judgment name: IKEA saved 17% and handed, though the crawler discovered much more textual content. Tune it by yourself pages.

Drawback 3: JavaScript Pages Come Again Empty

Three of the 4 JavaScript pages within the set construct their content material within the browser, so the HTML that requests will get is an app shell with virtually no textual content (the Notion assist web page had sufficient textual content in its HTML to go):

  • crates.io (serde): 4 seen phrases within the HTML. The plain conversion returned 16, Web site Content material Crawler 278.
  • Bluesky profile: 3 seen phrases within the HTML. The plain conversion returned 31, Web site Content material Crawler 135.
  • Mastodon profile: 4 seen phrases within the HTML. The plain conversion returned 26, Web site Content material Crawler 2,283.

The plain conversion has just a few extra phrases solely as a result of it retains the web page title and the “allow JavaScript” discover. No extractor can get better textual content that is not within the HTML. The needs_browser department of diagnose catches these, they usually want an actual browser. You may run Playwright your self, or hand the URLs to a hosted crawler. The take a look at used Web site Content material Crawler, a hosted crawler from Apify. It renders every web page, removes navigation and cookie banners, and returns Markdown. The code beneath wants apify-client 3 or later (pip set up “apify-client>=3”):

python

import os
from apify_client import ApifyClient

def render_with_crawler(urls):
    consumer = ApifyClient(os.environ["APIFY_TOKEN"])
    run = consumer.actor("apify/website-content-crawler").name(run_input={
        "startUrls": [{"url": u} for u in urls],
        "maxCrawlDepth": 0,               
        "crawlerType": "playwright:firefox",
        "respectRobotsTxtFile": True,
        "removeCookieWarnings": True,
    })
    objects = consumer.dataset(run.default_dataset_id).iterate_items()
    return {merchandise["url"]: merchandise["markdown"] for merchandise in objects}

[IMAGE: Grouped bar chart of words kept per page by trafilatura and Website Content Crawler: Apple 106 vs 1,513, Allbirds 200 vs 1,244, IKEA 412 vs 3,238, crates.io 12 vs 278, Bluesky 26 vs 135, Mastodon 21 vs 2,283]

Phrases saved per web page on the product and JavaScript pages.

Rendering doesn’t imply you’re completed, although. When the operate was rerun as a examine, crates.io got here again with 278 phrases once more, however the Bluesky profile got here again with 9 phrases as an alternative of 135. Pages like that may load content material in phases, so examine the rendered output too. The crawler returns Markdown, not HTML, so a phrase depend is sufficient: retry or wait longer if it is nonetheless skinny. Web site Content material Crawler has a waitForSelector setting for this case.

For those who’d slightly run the browser your self, Playwright does the rendering half. Set up it with pip set up playwright and playwright set up chromium, then go the rendered HTML by the identical main_region_markdown fallback from Drawback 2:

python

from playwright.sync_api import sync_playwright

def render_with_playwright(urls, settle_ms=2000):
    outcomes = {}
    with sync_playwright() as p:
        browser = p.chromium.launch()
        web page = browser.new_page(user_agent=HEADERS["User-Agent"])
        for url in urls:
            web page.goto(url, wait_until="networkidle", timeout=60_000)
            web page.wait_for_timeout(settle_ms)  
            outcomes[url] = main_region_markdown(web page.content material())
        browser.shut()
    return outcomes

On a take a look at web page that builds its content material in JavaScript, a plain request returned solely the “Loading…” placeholder, whereas this operate returned each headings and their paragraphs. You get full management and no per-page payment, however you additionally run, scale and replace the browsers your self, and you continue to want your personal dealing with for cookie banners and consent dialogs.

Drawback 4: Headings, Code, and Tables Get Misplaced

Phrase counts let you know whether or not textual content survived. They do not let you know whether or not the construction did, and RAG will depend on construction. Headings turn into chunk boundaries, code wants its indentation, and a desk that turns right into a run of numbers cannot reply “what is the restrict for X”.

Between them, two pages within the set confirmed all three issues with trafilatura:

  • GitHub’s REST API fee limits web page had 19 headings within the HTML and 0 within the output.
  • Python’s json docs had 17 desk rows within the HTML and 0 within the output. Code examples misplaced their indentation: def default(self, obj): and the traces of its physique got here out on the similar stage, which is not legitimate Python anymore.

Web site Content material Crawler saved 13 of the GitHub headings and all 17 desk rows on the Python web page. It is not excellent both. On the Python web page it saved 11 of 17 headings, and its code examples saved their indentation however got here out as plain textual content, with out code fences and with characters like [ and = escaped. On a short post by Simon Willison it kept 30 words where trafilatura kept 77.

So check structure on every page, whatever tool you use:

python

import re
from bs4 import BeautifulSoup

def count_code_blocks(markdown):
    fenced = markdown.count("```") // 2
    indented = len(re.findall(r"(?:^|nn)(?: {4}|t)S", markdown))
    return fenced + indented

def structure_report(html, markdown):
    soup = BeautifulSoup(html, "lxml")
    lines = markdown.splitlines()
    return {  
        "headings": (len(soup.select("h2, h3")), sum(bool(re.match(r"#{2,3} ", l)) for l in lines)),
        "code_blocks": (len(soup.select("pre")), count_code_blocks(markdown)),
        "table_rows": (len(soup.select("table tr")), sum(l.lstrip().startswith("|") and not re.fullmatch(r"[s|:-]+", l) for l in traces)),
    }

For the GitHub web page and trafilatura, it returns “headings”: (19, 0). Log pages the place the second quantity is way beneath the primary, and route them to a distinct technique.

Drawback 5: The Similar Navigation on Each Web page

Extractors decide every web page by itself by default (trafilatura has an non-compulsory deduplicate setting), so they do not see {that a} block seems on each web page of a website. Once you index a complete docs website, the menu, breadcrumbs, and “Skip to content material” hyperlinks get embedded as soon as per web page. Have a look at the positioning as a complete as an alternative:

python

import hashlib
import re
from collections import Counter

def _key(block):
    return hashlib.sha1(re.sub(r"W+", " ", block.decrease()).strip().encode()).hexdigest()

def drop_repeated_blocks(pages, min_pages=3):
    """pages: dict of url -> markdown from the identical website.
    Removes blocks (paragraphs, checklist objects) that seem on min_pages or extra pages."""
    blocks = {url: [b for b in md.split("nn") if b.strip()] for url, md in pages.objects()}
    seen = Counter(ok for bs in blocks.values() for ok in {_key(b) for b in bs})
    return {
        url: "nn".be part of(b for b in bs if seen[_key(b)] < min_pages)
        for url, bs in blocks.objects()
    }

In an additional take a look at exterior the 20-page set, on 4 GitHub REST docs pages transformed with plain markdownify, this eliminated 79 blocks from the primary web page alone (“Skip to predominant content material”, “Menu”, “Collapse sidebar”) and reduce the 4 pages from 34,207 tokens to 19,606, a 43% drop. On 4 Python library docs pages it eliminated only one.3%, as a result of Python’s navigation is small subsequent to the content material. Run it and measure; do not assume.

Set min_pages with care. On a small website, an actual paragraph that seems on three pages (a shared warning, say) might be eliminated. Headings are blocks too, so a piece title that repeats throughout pages, like “Parameters”, goes as effectively. For those who chunk by heading subsequent, skip blocks that begin with # if you depend.

Drawback 6: Chunks With out Context

The final step is splitting every web page into chunks for embedding. Splitting each N tokens cuts sections in half and loses the heading that claims what the textual content is about. Cut up on headings, maintain the heading path with every chunk, and solely cut up additional when a piece is just too lengthy:

python

import re
import tiktoken

ENC = tiktoken.get_encoding("o200k_base")
HEADING = re.compile(r"^(#{1,3})s+(.*)")
LINK = re.compile(r"[([^]]+)]([^)]*)")

def sections(markdown):
    path, buf, in_code = [], [], False
    for line in markdown.splitlines():
        in_code ^= line.startswith("```")
        m = None if in_code else HEADING.match(line)
        if m:
            yield " > ".be part of(path), "n".be part of(buf).strip()
            path = path[: len(m.group(1)) - 1] + [LINK.sub(r"1", m.group(2)).strip()]
            buf = []
        else:
            buf.append(line)
    yield " > ".be part of(path), "n".be part of(buf).strip()

def chunk_markdown(markdown, source_url, max_tokens=400):
    chunks = []
    for part, textual content in sections(markdown):
        half = []
        for para in filter(None, textual content.cut up("nn")):
            if half and len(ENC.encode("nn".be part of(half + [para]))) > max_tokens:
                chunks.append({"url": source_url, "part": part, "textual content": "nn".be part of(half)})
                half = []
            half.append(para)
        if half:
            chunks.append({"url": source_url, "part": part, "textual content": "nn".be part of(half)})
    return chunks

That is the place Drawback 4 comes again. The trafilatura output for the GitHub web page gave 8 chunks, none with a piece path, as a result of it had no headings. The crawler’s output gave 15 chunks, every labeled like “Price limits for the REST API > About major fee limits > Main fee restrict for unauthenticated customers”. Retailer part and url as metadata, and put the part path on the high of the textual content you embed.

One restrict: a single paragraph or code block longer than max_tokens stays entire. On the Python docs, one chunk was 1,137 tokens. Cut up these additional in case your embedding mannequin wants it.

Placing It Collectively

A pipeline that holds up on blended pages appears to be like like this:

  1. Fetch the web page (see the fetch-layer information linked above).
  2. Extract the primary content material with trafilatura.
  3. Run diagnose. Render needs_browser pages in a browser; convert extractor_dropped_content pages with the main-region fallback.
  4. Run structure_report and route pages that misplaced headings, code, or tables to a different technique.
  5. Drop blocks repeated throughout the positioning.
  6. Chunk by heading, with the part path and URL as metadata.

The takeaway from this take a look at: do not decide one converter for every thing. trafilatura gave the leanest output total. The rendering crawler was the one technique that bought the JavaScript pages, and it saved extra of the docs construction than trafilatura, at the price of a browser per web page. The take a look at did not run trafilatura on rendered HTML, so a part of that hole could come from rendering, not extraction, and a few of trafilatura’s lean output is content material it dropped (Drawback 2). The checks between the steps are what make both of them protected to make use of.

Wrapping Up

Each drawback discovered on this take a look at got here from the conversion step: navigation embedded as content material, product pages decreased to a paragraph, JavaScript pages listed as empty, and docs with out headings. Measure every web page you change, utilizing phrase counts in opposition to the seen textual content and construction counts in opposition to the HTML, and ship the failures down a distinct path. Begin with the diagnose and structure_report features above on a pattern of your personal pages. They run regionally on HTML you have already got and let you know which of those issues you may have.

FAQs

Why convert to Markdown as an alternative of plain textual content?

Markdown retains headings, lists, tables, and code blocks, so your chunker can cut up on them and a big language mannequin (LLM) can see the construction. Plain textual content loses that construction, and with it the chunk boundaries and part labels.

Maintain them in case your solutions ought to cite or observe them. Drop them in the event that they’re largely navigation. Within the take a look at, plain conversions had 5,444 hyperlinks throughout 20 pages; after extraction, 909 have been left.

Is it OK to gather pages for RAG?

Verify every website’s phrases and robots.txt, determine your bot actually, and maintain request charges low. The fetch-layer information linked above covers this intimately. Web site Content material Crawler has a setting to respect robots.txt, which was turned on for this take a look at.

How huge ought to chunks be?

There is no single proper measurement. The examples right here use 400 tokens as a restrict and headings as the primary boundary. Take a look at just a few sizes in opposition to actual questions out of your customers and maintain the one which retrieves the correct part most frequently.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments