Skip to content
James Ross
articlePublished Updated 8 min read

Self-Healing Scrapers: Letting an LLM Repair Broken Recipes

By James Ross

Self-healing scrapers detect a broken extraction recipe, ask a model for a candidate fix, validate that fix against stored page snapshots, and queue it for human approval. The loop is only safe when detection and validation are deterministic and the model never writes straight to production.

A cracked extraction gear replaced by a model-proposed part tested against snapshot cards, showing a self-healing scraper.

This is the maintenance layer for the kind of pipeline described in daily stock checks at big-box retailers, where a handful of selectors stand between a working report and a silent gap.

What is a scraper recipe?

A recipe is the part of a scraper that knows where the data lives on one site: which element holds the price, which attribute holds the stock state, how to clean a currency string, and what a valid result looks like. It is data, not code, and it should be versioned like data.

A workable recipe has four parts:

  • Identity. The site, the page archetype, and the URL pattern it applies to.
  • Selectors. Where each field comes from, written as role, text, or attribute locators where possible.
  • Normalisers. How a raw string becomes a typed value: "$1,299.00" becomes 1299.00, "Only 3 left" becomes 3.
  • Assertions. What must be true for the result to count: a price in a plausible range, an availability value from an allowed set, a non-empty title.

Keeping the recipe separate from the runner is what makes repair possible. If the selector is buried in a function, every fix is a deploy. If it is a versioned record, a fix is a review.

How do you know a recipe broke?

A recipe has broken when it stops producing a complete, plausible result for a page that still exists. The distinction that matters is between a page that changed, a page that refused, and a page that rendered late.

Four signals catch most breaks:

  1. Zero yield. The selector matches nothing. Usually a class rename or a layout change.
  2. Field-level nulls. The row exists but the price or availability is missing. Often a conditional layout, such as a price shown only after a location is set.
  3. Confidence drop. The extractor still returns a value but its own confidence score falls below the threshold. On the price platform above, that threshold is 0.8 by default, and a low-confidence observation cannot open a violation.
  4. Canary mismatch. A synthetic page with known values, run through the same recipe, returns something different. This is the only signal that catches a wrong value that still looks plausible.

The fourth signal is the one teams skip and the one that pays for itself. Zero-yield breaks get noticed because the report is empty. A selector that now matches a different element produces a confident wrong number, and nothing in the pipeline complains.

The other half of detection is ruling out the page. A recipe that returns nothing because the browser got an access-denied screen is not broken. Recording blocked separately from failed keeps the repair queue free of false repairs.

What does the repair loop look like?

The loop is a pipeline with a human gate at the end. The model proposes; the system disposes.

  1. Freeze the evidence. Store the failing page’s HTML, a screenshot, the URL, the timestamp, and the recipe version. Repair without evidence is guesswork.
  2. Classify the failure. Blocked, timeout, empty, partial, or low confidence. Only the last three are recipe problems.
  3. Build a bounded prompt. Send the recipe contract, the failing fields, and a trimmed HTML sample. Never send cookies, tokens, or a full page with account data in it.
  4. Ask for a candidate, not a patch. Request a complete recipe object that matches the schema, plus a one-line rationale per changed field.
  5. Schema-validate the response. Parse it against a strict Zod schema; reject anything that is not shaped like a recipe.
  6. Replay against snapshots. Run the candidate over stored pages with known values, including pages that currently work.
  7. Score and diff. Compare per-field results with the golden values, and show the diff against the live recipe.
  8. Approve, publish, shadow. A human approves, the recipe gets a new version, and it runs in shadow against the live one before it is promoted.

Steps 5 and 6 are where the loop earns trust. A model will happily return a selector that matches the page in front of it and nothing else; only the snapshot set tells you whether it also matches last month’s pages.

import { z } from "zod";

const RecipeCandidate = z.object({
  site: z.string().min(1),
  archetype: z.string().min(1),
  fields: z.object({
    price: z.object({
      locator: z.string().min(1),
      normalize: z.enum(["decimal", "integer", "text"]),
    }),
    availability: z.object({
      locator: z.string().min(1),
      map: z.record(z.string(), z.enum(["in_stock", "out_of_stock", "unknown"])),
    }),
  }),
  assertions: z.object({
    price_min: z.number().nonnegative(),
    price_max: z.number().positive(),
  }),
  rationale: z.string().max(500),
});

The schema is deliberately narrower than the page. A repair can change how a price or an availability value is read. It cannot add a field, change a URL pattern, or widen an assertion, because those are product decisions rather than extraction bugs.

What should the model see?

It should see the smallest page fragment that contains the failing field, plus the contract it has to satisfy. Everything else is noise that increases the chance of a confident wrong answer.

The practical rules:

  • Strip the chrome. Navigation, footers, cookie banners, and script tags add tokens and distract from the field.
  • Redact account state. Prices can be personalised, and a logged-in page may hold a name, an order number, or an address. Build the prompt from the redacted snapshot.
  • Bound the size. A fixed token budget per request, with the failing region prioritised.
  • Include the previous recipe and its failure. The model needs to know what it is replacing and which field failed, or it will rewrite everything.

How do you validate a candidate recipe?

Validate against a fixed set of stored pages with known values, and require the candidate to beat the live recipe rather than merely match the page that failed.

A validation set needs three kinds of page:

  • The failing page. The one that triggered the repair.
  • Working pages for the same archetype. Two or three that currently extract correctly. A candidate that breaks them is rejected.
  • Edge cases. A page with no price, a page with a sale price, a page with the item out of stock. These are where confident wrong answers come from.

Each field gets an assertion and the run gets a pass or fail. A price off by a cent is a fail. Availability mapping a new string to unknown instead of crashing is a pass with a warning, because unknown is an honest answer.

The last step is a shadow run: publish the candidate to a small slice of the schedule and compare its output with the live recipe for a day. That catches the pages nobody thought to snapshot.

Manual fix, heuristics, model repair or an agent?

The options differ in who writes the new selector and how much review they need.

Manual fix Heuristic repair Model-assisted repair Agent that browses
Who finds the new selector an engineer rules over the DOM a model, from evidence an agent, live
Time to a candidate hours to days minutes minutes minutes
Quality on a familiar layout high medium high varies
Quality on a redesign high low medium medium
Review burden low medium medium high
Failure mode slow wrong match plausible wrong recipe unpredictable actions
Needs stored evidence no yes yes no

Which should you choose? Use a manual fix when the site is small or the change is structural. Use heuristics when the field is simple and the layout is regular, such as a JSON-LD price that only needs a new property. Use model-assisted repair when there are many sites, a stable snapshot set, and a human who can review a diff in a minute. Avoid a live browsing agent for extraction repair: it changes the page it is diagnosing, and its actions are harder to review than a recipe object.

How do you ship a repair safely?

Ship it as a new version with a diff, a rollback, and a per-version metric. The model’s output is a proposal; the release is still a release.

The minimum:

  • Immutable versions. Every version keeps its full definition, its creation time, and the evidence behind it.
  • A diff view. Old and new locator for each field, side by side, with the validation result underneath.
  • One-step rollback. Reverting to the previous version should not require a deploy.
  • Per-version telemetry. Yield, confidence, and null rate by version. A new version that quietly halves the yield is worse than the break it fixed.
  • An owner. A queue with no owner rots, even when the fix takes a minute to approve.

What broke and what we changed

A valid page was diagnosed as a broken recipe. A store checker reported a missing availability box on valid pages. The page was fine and the inventory response behind it was returning data; the widget had not initialised. The repair queue would have spent that time rewriting correct selectors. The fix was to classify the failure first: no inventory response is a page or session problem, a response with no rendered widget is a rendering problem, and a response with the wrong shape is a recipe problem.

The extractor’s fallback was treated as the answer. The generic extractor reads the first JSON-LD Offer on the page or falls back to basic metadata. On a page with several offers, “first” is a choice rather than a fact, and the project’s own findings recorded that the path had only synthetic tests behind it. Make the fallback explicit in the output — a source value on every observation — so a report can show whether a price came from a dedicated adapter, JSON-LD, or metadata.

The evidence contract disagreed with itself. The reports UI described screenshot plus extracted text, the monitor wrote screenshot plus HTML, and the code and the database used different names for the same evidence type. A validator cannot prove a case is evidence-ready when the schema has two words for one thing. The fix is one canonical vocabulary, defined once and enforced at the boundary.

Report filters were stored and never applied. A requested date range was saved with the request but the worker ignored it, so two different requests produced the same file. Validate the artifact, not the request that produced it.

Frequently asked questions

What is a self-healing scraper?

A self-healing scraper detects that its extraction recipe no longer produces a valid result, generates a candidate replacement, tests that candidate against stored pages, and routes it to a human for approval. The healing is in the detection and the candidate generation. The release is still a reviewed change.

How does an LLM repair a broken selector?

It receives the failing field, the previous recipe, and a trimmed sample of the page, then returns a complete recipe object with new locators and a short rationale. The useful output is structured, not prose, so it can be schema-validated and replayed. A model that returns a paragraph of advice has not repaired anything.

Is it safe to let a model change production scrapers?

Not directly. The safe pattern is proposal, validation, approval, and a shadow run. The model never holds credentials, never writes to the live recipe, and never decides that its own output is correct. With those limits, the worst case is a rejected candidate rather than a silent wrong number.

How do you detect a broken scraper?

Watch four things: zero-yield runs, field-level nulls, a drop in extraction confidence, and canary pages with known values. The canary is the only one that catches a selector which now matches the wrong element, because that failure still produces a value.

Why validate against snapshots instead of the live page?

Because the live page changes and the snapshot does not. A candidate tuned to a layout that appeared an hour ago may match today's page and nothing else. A fixed snapshot set, including pages that already work, shows whether the repair generalises or just fits the failure.

Can recipe repair handle a full site redesign?

Partly. A redesign that keeps the same data in a different structure is a good candidate for model-assisted repair, because the fields still exist and the snapshot set can prove the mapping. A redesign that removes a field, or moves it behind a login, is a product change and needs a decision rather than a selector.

Do you still need a human in the loop?

Yes, for anything that reaches a customer or a compliance decision. The review is short — a diff, a validation result, and a rationale — but it is the step that keeps a plausible wrong recipe out of production. Automate the rest.