A scraper can return a clean, valid record that is wrong. The price is a number, the rating is between one and five, every required field is filled, and every value belongs to the card next to the one you wanted. Checks on the shape of a record can't see that. Scraping data quality metrics need a reference: values a person read off the page, to compare the extraction against.
This tutorial builds a small evaluation suite that measures three things separately: record coverage, missing-field rate and field accuracy. It defines every denominator, scores each field with a confidence interval, and puts the wrong values that look right in front of a reviewer.
We will need to use Spidra, so install the package and put your Spidra key in the environment as SPIDRA_API_KEY:
# pip install spidra
import argparse
import csv


import difflib
import hashlib
import json
import os
import sys
import unicodedata
from collections import Counter
from math import sqrt
from pathlib import Path
from spidra import ScrapeParams, ScrapeUrl, Spidra, SpidraError
A valid record is not a correct record
Here is an extracted record for a book:
record = {"key": "book-03", "price": 14.99, "rating": 4}
price_ok = isinstance(record["price"], float) and record["price"] > 0
valid = price_ok and record["rating"] in (1, 2, 3, 4, 5)
print("passes validation:", valid)
Output:
passes validation: True
It passes. On the page, that book costs 30.99, and 14.99 is the price of the card beside it. Validation with Pydantic catches values that are malformed, and you should use it. It can't catch values that are well-formed and wrong, so you have to measure those against something you trust.
Three questions, three denominators
Quality numbers are only comparable if you say what each one is divided by. Every cell in the dataset, one field of one record, gets exactly one of five outcomes, depending on whether the reference shows a value and whether the extraction returned one:
| Outcome | The reference | The extraction |
|---|---|---|
| correct | has a value | matches it |
| wrong | has a value | returned a different one |
| missed | has a value | is empty |
| correct_null | has no value | is empty |
| invented | has no value | returned one anyway |
The metrics are shares of those outcomes, and each names its denominator:
| Metric | The question | Formula |
|---|---|---|
| Record coverage | Did you get the records you should have? | expected records found ÷ expected records |
| Field accuracy | Of the values the page shows, how many are right? | correct ÷ reference values |
| Missing-field rate | Of the values the page shows, how many did you leave empty? | missed ÷ reference values |
| Wrong rate | Of the values the page shows, how many are wrong? | wrong ÷ reference values |
| Invention rate | Of the blanks, how many did you fill? | invented ÷ reference blanks |
| End-to-end accuracy | Of every value you should have got, how many are right? | correct ÷ reference values in all expected records |
Field accuracy, missing-field rate and wrong rate share one denominator, so they add up to 100% for every field. That's a useful check on your own code. Field metrics are computed over the records you found. End-to-end accuracy counts every value in a record you didn't find as missed, so coverage is folded into it. Publish both, and say which one you mean.
Match values the way a person would
Before you can count a value as correct, decide what "the same" means for each field. Too strict, and Ash And Ember scores as wrong against Ash and Ember. Too loose, and a price with a stray symbol scores as correct. These helpers normalize text and numbers, and refuse to treat a boolean as a number:
TRUE = {"true", "yes", "y", "1"}
FALSE = {"false", "no", "n", "0"}
def text(value):
"""Unicode-normalized, one space between words, no case."""
return " ".join(unicodedata.normalize("NFKC", str(value)).split()).casefold()
def number(value):
"""A float, or None. A boolean is not a number here."""
if isinstance(value, bool):
return None
try:
return float(value)
except (TypeError, ValueError):
return None
def as_bool(value):
if isinstance(value, bool):
return value
word = text(value) if isinstance(value, str) else None
return True if word in TRUE else False if word in FALSE else None
def exact(a, b):
return a == b
def normalized(a, b):
return text(a) == text(b)
def numeric(tolerance=0.005):
def same(a, b):
x, y = number(a), number(b)
return x is not None and y is not None and abs(x - y) <= tolerance
return same
def integer(a, b):
x, y = number(a), number(b)
return x is not None and y is not None and x.is_integer() and y.is_integer() and x == y
def boolean(a, b):
x, y = as_bool(a), as_bool(b)
return x is not None and x == y
def fuzzy(min_ratio=0.9):
def same(a, b):
return difflib.SequenceMatcher(None, text(a), text(b)).ratio() >= min_ratio
return same
def same_set(a, b):
def items(value):
parts = value if isinstance(value, (list, tuple, set)) else str(value).split(";")
return {text(part) for part in parts if text(part)}
return items(a) == items(b)
Each field gets one rule, chosen once and published with the results:
| Field | Rule | Why |
|---|---|---|
| title | normalized | Case and spacing aren't errors. |
| price | numeric(0.005) | Rounding isn't an error, but £15.99 as text is. |
| rating | integer | One star out is wrong. |
| in_stock | boolean |
yes and True mean the same. |
| long text | fuzzy(0.9) | Only for descriptions, and the threshold is yours to defend. |
COMPARATORS = {
"exact": lambda: exact,
"normalized": lambda: normalized,
"integer": lambda: integer,
"boolean": lambda: boolean,
"set": lambda: same_set,
"numeric": numeric,
"fuzzy": fuzzy,
}
def parse_match(rule):
"""'price=numeric:0.005' -> ('price', comparator)."""
field, _, how = rule.partition("=")
name, _, argument = how.partition(":")
if not field or name not in COMPARATORS:
raise ValueError(f"unknown match rule {rule!r}. Use field=name or field=name:argument")
return field, COMPARATORS[name](float(argument)) if argument else COMPARATORS[name]()
Build the reference set
The reference set is the part that costs effort, and the part every number depends on. Here is the method:
- Sample the pages you'll run in production. Take them from each page template or site separately, because accuracy on one layout says nothing about another.
- Write a field guide first. Say what counts as the price, what a rating is, and what to do when the page shows nothing. Leave the cell blank. Don't write N/A, because a blank is the label for "the page doesn't show it".
- Label from the page, not from the extraction. A person who sees the extractor's output will agree with it.
- Freeze the page. Pages change. Keep a snapshot or a date with each row, so the label and the extraction describe the same page.
- Double-label a fifth of the records, measure agreement, and have a third person settle every disagreement.
- Split the set. Tune your prompt on one half and report on the other.
The sheet is one row per record, in a plain CSV:
key,url,snapshot,title,price,rating,in_stock,discount_price,labeler
book-01,https://example.com/p/1,2026-11-19,Night Ferry,16.99,2,yes,,ana
book-08,https://example.com/p/8,2026-11-19,Glass Harbour,19.99,4,no,7.99,ana
Reading it, and any extraction in JSON Lines, goes through one function. A blank cell becomes None, and everything else is kept as written. A zero or a False is a value, not a blank:
def clean(value):
"""A blank cell means the page doesn't show the value. Everything else is kept as written."""
if isinstance(value, str):
value = value.strip()
return None if value == "" else value
def read_rows(path):
path = Path(path)
if path.suffix == ".csv":
with path.open(newline="", encoding="utf-8") as handle:
return list(csv.DictReader(handle))
if path.suffix == ".jsonl":
lines = path.read_text(encoding="utf-8").splitlines()
return [json.loads(line) for line in lines if line.strip()]
raise ValueError(f"unsupported file type: {path.suffix or path.name}")
def by_key(rows, key, fields):
"""({key: {field: value}}, duplicate keys). The first row with a key is the one that counts."""
records, duplicates = {}, []
for row in rows:
name = clean(row.get(key))
if name is None:
raise ValueError(f"a row has no {key!r}")
if str(name) in records:
duplicates.append(str(name))
else:
records[str(name)] = {field: clean(row.get(field)) for field in fields}
return records, duplicates
def load_reference(path, key, fields):
"""The reference set must be unique, non-empty and have every column it is scored on."""
rows = read_rows(path)
missing = [c for c in [key, *fields] if rows and c not in rows[0]]
if missing:
raise ValueError(f"columns missing from the reference set: {missing}")
records, duplicates = by_key(rows, key, fields)
if duplicates:
raise ValueError(f"duplicate keys in the reference set: {duplicates[:5]}")
if not records:
raise ValueError("the reference set is empty")
return records
The loader refuses a reference set with a repeated key, a missing column, or no rows. A reference set you can't trust is worse than none.
Agreement between two labelers tells you how well your field guide works. Count the records where they wrote the same value, and for category fields add Cohen's kappa, which discounts the agreement you'd get by chance:
def agreement(labels_a, labels_b, fields, spec=None):
"""{field: (agreed, compared)} over the records both people labeled."""
spec, shared = spec or {}, [k for k in labels_a if k in labels_b]
table = {}
for field in fields:
same = spec.get(field, normalized)
pairs = [(labels_a[k][field], labels_b[k][field]) for k in shared]
agreed = sum(
a is None and b is None or a is not None and b is not None and same(a, b)
for a, b in pairs
)
table[field] = (agreed, len(pairs))
return table
def cohens_kappa(a, b):
"""Agreement beyond chance, for category labels. None when chance alone explains everything."""
n = len(a)
if n == 0 or n != len(b):
return None
observed = sum(x == y for x, y in zip(a, b)) / n
count_a, count_b = Counter(a), Counter(b)
chance = sum(count_a[c] * count_b[c] for c in count_a) / (n * n)
return None if chance == 1 else (observed - chance) / (1 - chance)
def disagreements(labels_a, labels_b, fields, spec=None):
"""The (key, field, a, b) rows a third person has to settle."""
spec, rows = spec or {}, []
for key in labels_a:
for field in fields if key in labels_b else []:
a, b = labels_a[key][field], labels_b[key][field]
if not (
a is None
and b is None
or a is not None
and b is not None
and spec.get(field, normalized)(a, b)
):
rows.append((key, field, a, b))
return rows
def adjudicate(labels_a, disagreement_rows, decisions):
"""Labels A with every disagreement replaced by the decision. A missing decision is an error."""
final = {key: dict(record) for key, record in labels_a.items()}
for key, field, _, _ in disagreement_rows:
if (key, field) not in decisions:
raise ValueError(f"no decision for {key} / {field}")
final[key][field] = decisions[(key, field)]
return final
Here are two labelers on ten made-up in-stock labels, with two disagreements:
a = ["yes", "yes", "no", "yes", "no", "yes", "yes", "no", "yes", "yes"]
b = ["yes", "yes", "no", "no", "no", "yes", "yes", "no", "yes", "no"]
print("agreed on", sum(x == y for x, y in zip(a, b)), "of", len(a))
print("kappa:", round(cohens_kappa(a, b), 2))
Output:
agreed on 8 of 10
kappa: 0.6
Eight of ten is 80% agreement, and kappa is lower, because with only two labels some agreement happens by luck. Settle each disagreement with a third reader, and rewrite the field guide where the same confusion keeps coming back.
To keep the split honest, assign each record to a half by its key, so nobody can move a record to improve a score:
def split_of(key, test_share=0.5, salt="v1"):
"""'dev' or 'test', decided by the key alone. The same key always lands in the same half."""
digest = hashlib.sha256(f"{salt}:{key}".encode("utf-8")).digest()
return "test" if int.from_bytes(digest[:8], "big") / 2**64 < test_share else "dev"
halves = [split_of(f"book-{i:02d}") for i in range(20)]
print(Counter(halves))
print("book-03 is in the", split_of("book-03"), "half")
Output:
Counter({'dev': 13, 'test': 7})
book-03 is in the dev half
Score the extraction
For the examples, here are twenty made-up books and a copy with the mistakes an extractor makes. Every mistake is in the code, so you can see exactly what the scores are measuring:
TITLES = (
"Salt Road;Night Ferry;The Quiet Annex;Paper Moons;Low Tide;A Thousand Doors;Ash and Ember;"
"The Long Shift;Glass Harbour;Cold Open;Iron Lilies;Small Hours;The Last Ledger;"
"North of Nowhere;Winter Orchard;Red Signal;The Hollow Clock;Tin Kingdom;Soft Landing;Blue Hour"
).split(";")
def build_reference():
"""Only product 8 has a discount price. For the other nineteen the page shows none."""
return [
{
"key": f"book-{i:02d}",
"title": title,
"price": round(9.99 + (i * 7) % 23, 2),
"rating": 1 + i % 5,
"in_stock": i % 4 != 0,
"discount_price": 7.99 if i == 8 else None,
}
for i, title in enumerate(TITLES)
]
def seed_values(rows):
"""Wrong, missed and invented values, as extractors produce them."""
rows["book-03"]["price"] = rows["book-04"]["price"] # the price from the next card
rows["book-09"]["price"] = round(rows["book-09"]["price"] * 10, 2) # a decimal point lost
rows["book-14"]["price"] = "£15.99" # a symbol left in
rows["book-11"]["price"] = rows["book-12"]["rating"] = rows["book-18"]["rating"] = None
rows["book-05"]["rating"] = 2 # one star out
rows["book-02"]["in_stock"] = rows["book-10"]["in_stock"] = False # flipped
rows["book-06"]["title"] = "Ash and" # cut short
rows["book-10"]["title"] += " (Paperback)" # a label that isn't part of the title
rows["book-01"]["discount_price"], rows["book-15"]["discount_price"] = 8.49, 5.99 # invented
def seed_records(rows):
"""Records never found, a record from a related-items strip, and one extracted twice."""
for key in ("book-07", "book-13", "book-16"):
del rows[key]
rows["book-99"] = {
"key": "book-99",
"title": "Old Edition",
"price": 9.99,
"rating": 3,
"in_stock": True,
}
return [*rows.values(), dict(rows["book-05"])]
def build_extraction(reference):
rows = {r["key"]: dict(r) for r in reference}
seed_values(rows)
return seed_records(rows)
The scoring is five small functions. outcome decides one cell, coverage counts records, score_cells and tally apply it to every found record, and rates turns the counts into the shares in the table above:
OUTCOMES = ("correct", "correct_null", "wrong", "missed", "invented")
def outcome(gold, got, same=normalized):
"""The reference either shows a value or it doesn't. So does the extraction."""
if gold is None:
return "correct_null" if got is None else "invented"
if got is None:
return "missed"
return "correct" if same(gold, got) else "wrong"
def coverage(reference, extracted):
"""Record coverage = expected records found / expected records. Extras are counted too."""
found = [key for key in reference if key in extracted]
return {
"expected": len(reference),
"found": len(found),
"missing": [key for key in reference if key not in extracted],
"extra": [key for key in extracted if key not in reference],
}
def score_cells(reference, extracted, fields, spec=None):
"""{key: {field: outcome}}, for expected records that were found. Not for the others."""
spec = spec or {}
return {
key: {
f: outcome(reference[key][f], extracted[key].get(f), spec.get(f, normalized))
for f in fields
}
for key in reference
if key in extracted
}
def tally(cells, fields):
table = {field: Counter() for field in fields}
for record in cells.values():
for field, result in record.items():
table[field][result] += 1
return table
def share(part, whole):
return part / whole if whole else None
def rates(counts):
"""Accuracy, missing rate and wrong rate share one denominator, so they add up to 100%."""
values = counts["correct"] + counts["wrong"] + counts["missed"]
empty = counts["correct_null"] + counts["invented"]
return {
"accuracy": share(counts["correct"], values),
"missing_rate": share(counts["missed"], values),
"wrong_rate": share(counts["wrong"], values),
"invention_rate": share(counts["invented"], empty),
"values": values,
"empty_cells": empty,
}
def end_to_end(reference, table, fields):
"""Accuracy over every value the reference holds. An unfound record counts as missed."""
values = sum(1 for record in reference.values() for f in fields if record[f] is not None)
correct = sum(counts["correct"] for counts in table.values())
return {"accuracy": share(correct, values), "values": values, "correct": correct}
def exact_record_rate(reference, cells):
"""Share of expected records with every field right. An unfound record can't be."""
exact = sum(
all(r in ("correct", "correct_null") for r in record.values()) for record in cells.values()
)
return {"rate": share(exact, len(reference)), "records": exact, "expected": len(reference)}
A share from a handful of values is a rough estimate, so every accuracy comes with a 95% Wilson interval, which stays inside 0 and 100%:
def wilson(hits, n, z=1.96):
"""A 95% interval for a share. With few cells it is wide, which is the point."""
if not n:
return (0.0, 0.0)
p, centre = hits / n, 1 + z * z / n
spread = z * sqrt(p * (1 - p) / n + z * z / (4 * n * n))
low, high = (p + z * z / (2 * n) - spread) / centre, (p + z * z / (2 * n) + spread) / centre
return (max(0.0, low), min(1.0, high))
Now the report: one function collects every number, and the others format it.
def summarize(reference, extracted_rows, key, fields, spec=None):
"""Everything the report prints, as numbers. The denominators are in the result."""
extracted, duplicates = by_key(extracted_rows, key, fields)
cells = score_cells(reference, extracted, fields, spec)
table = tally(cells, fields)
return {
"coverage": coverage(reference, extracted),
"duplicates": duplicates,
"table": table,
"rates": {field: rates(table[field]) for field in fields},
"end_to_end": end_to_end(reference, table, fields),
"exact": exact_record_rate(reference, cells),
"cells": cells,
"extracted": extracted,
}
def pct(value):
return "n/a" if value is None else f"{value:.0%}"
def interval(hits, n):
low, high = wilson(hits, n)
return f"{low:.0%} to {high:.0%}"
def names(keys):
return ", ".join(keys) or "none"
def row_cells(summary, field):
r, c = summary["rates"][field], summary["table"][field]
accuracy = (
f"{pct(r['accuracy'])} ({interval(c['correct'], r['values'])})" if r["values"] else "n/a"
)
cells = [field, accuracy, pct(r["missing_rate"]), pct(r["wrong_rate"]), r["values"]]
return [*cells, pct(r["invention_rate"]), r["empty_cells"]]
def field_rows(summary, fields):
head = [
"field",
"accuracy (95% interval)",
"missing",
"wrong",
"values",
"invention",
"empty cells",
]
rows = ["| " + " | ".join(head) + " |", "|---|---|---|---|---|---|---|"]
return rows + ["| " + " | ".join(map(str, row_cells(summary, f))) + " |" for f in fields]
def coverage_lines(cov, duplicates):
share = pct(cov["found"] / cov["expected"])
span = interval(cov["found"], cov["expected"])
return [
f"Record coverage: {cov['found']}/{cov['expected']} ({share}, 95% interval {span})",
f"Missing records: {names(cov['missing'])}",
f"Extra records: {names(cov['extra'])} | duplicates: {names(duplicates)}",
]
def render(summary, fields):
e2e, exact = summary["end_to_end"], summary["exact"]
lines = coverage_lines(summary["coverage"], summary["duplicates"])
lines += ["", *field_rows(summary, fields), ""]
lines.append(f"End-to-end accuracy: {e2e['correct']}/{e2e['values']} ({pct(e2e['accuracy'])})")
lines.append(f"Exact records: {exact['records']}/{exact['expected']} ({pct(exact['rate'])})")
return "\n".join(lines)
fields = ["title", "price", "rating", "in_stock", "discount_price"]
reference, _ = by_key(build_reference(), "key", fields)
spec = {"price": numeric(), "rating": integer, "in_stock": boolean}
summary = summarize(reference, build_extraction(build_reference()), "key", fields, spec)
print(render(summary, fields))
Output:
Record coverage: 17/20 (85%, 95% interval 64% to 95%)
Missing records: book-07, book-13, book-16
Extra records: book-99 | duplicates: book-05
| field | accuracy (95% interval) | missing | wrong | values | invention | empty cells |
|---|---|---|---|---|---|---|
| title | 88% (66% to 97%) | 0% | 12% | 17 | n/a | 0 |
| price | 76% (53% to 90%) | 6% | 18% | 17 | n/a | 0 |
| rating | 82% (59% to 94%) | 12% | 6% | 17 | n/a | 0 |
| in_stock | 88% (66% to 97%) | 0% | 12% | 17 | n/a | 0 |
| discount_price | 100% (21% to 100%) | 0% | 0% | 1 | 12% | 16 |
End-to-end accuracy: 58/81 (72%)
Exact records: 5/20 (25%)
Three of the twenty records were never found, so coverage is 85%, with an interval that runs from 64% to 95%. One record came from a related-items strip and is reported without being scored, and one was extracted twice, so only its first copy counts.
The four fields every record has sit between 76% and 88%, and that is the misleading part. Only 5 of 20 records are fully right. A buyer who sees "about 85% accurate" imagines most records are fine, and most aren't.
The two bottom lines differ for a reason. Of the values in the records you found, 84% are right, but of the values you should have got, 72% are. A record that was never found costs you every value in it.
Look at discount_price. Only one record shows a discount, so its accuracy is 1 of 1, and the interval runs from 21% to 100%. A perfect score from one value means almost nothing. The number that matters for that field is the invention rate: 2 of the 16 blanks were filled with a value the page doesn't show.
Don't average the problem away
Aggregates hide the most useful failure. On a live category page of a practice bookshop site, with 20 books and a reference read from the page's own markup, a Scrape with a schema returned every price and every stock status correctly. For the star rating it returned nothing at all, for all 20 books, because the site draws stars as a CSS class and not as text. In outcomes:
live = {
"price": Counter(correct=20),
"rating": Counter(missed=20),
"in_stock": Counter(correct=20),
}
for field, counts in live.items():
r = rates(counts)
low, high = wilson(counts["correct"], r["values"])
print(f"{field:9s} accuracy {r['accuracy']:.0%} ({low:.0%} to {high:.0%})", end=" | ")
print(f"missing {r['missing_rate']:.0%} | wrong {r['wrong_rate']:.0%}")
Output:
price accuracy 100% (84% to 100%) | missing 0% | wrong 0%
rating accuracy 0% (0% to 16%) | missing 100% | wrong 0%
in_stock accuracy 100% (84% to 100%) | missing 0% | wrong 0%
Rating is a 100% missing-field rate and a 0% wrong rate. The extractor didn't guess.
That tells you what to fix. A prompt can't recover a value that isn't in the text, so the fix is a different way to read the page. A shortcut that compares extracted == reference scores the field 0%, the same as a field that returns confident wrong values, which needs a different fix. Count missed and wrong apart, and the number points to the cause.
Twenty correct values also aren't 100%. The interval for price starts at 84%.
Surface the errors for review
Scores say how much is wrong. A person still has to look at what. This turns every wrong, invented and missed value into a row, wrong values first and heavier fields before lighter ones. It guesses how each wrong value went wrong, and records whether the value would have passed a validator:
PRIORITY = {"wrong": 0, "invented": 1, "missed": 2}
VALIDATORS = {
"price": lambda v: number(v) is not None and number(v) > 0,
"rating": lambda v: number(v) is not None and number(v) in (1, 2, 3, 4, 5),
"in_stock": lambda v: isinstance(v, bool),
"title": lambda v: isinstance(v, str) and v.strip() != "",
}
def passes_validation(field, value):
"""True if the value has a valid shape. A wrong value that passes is a plausible one."""
check = VALIDATORS.get(field)
return None if value is None or check is None else bool(check(value))
def numeric_error(gold, got):
x, y = number(gold), number(got)
if x is None or y is None or x == 0:
return None
if any(abs(y / x - r) < 0.01 for r in (10, 100, 0.1, 0.01)):
return "decimal_shift"
return "off_by_one" if x.is_integer() and y.is_integer() and abs(x - y) == 1 else None
def error_type(gold, got, others, same=normalized):
"""A best guess at how a wrong value went wrong. It sorts the queue. A person decides."""
if gold is None:
return "invented"
if got is None:
return "missed"
if isinstance(gold, bool) and isinstance(got, bool):
return "flipped"
if (kind := numeric_error(gold, got)) is not None:
return kind
if any(same(got, other) for other in others):
return "adjacent_record"
if text(gold).startswith(text(got)):
return "truncated"
return "extra_text" if text(gold) in text(got) else "other"
def review_row(reference, extracted, key, field, result, spec):
gold, got = reference[key][field], extracted[key].get(field)
others = [rec[field] for k, rec in reference.items() if k != key and rec[field] is not None]
return {
"key": key,
"field": field,
"outcome": result,
"reference": gold,
"extracted": got,
"error_type": error_type(gold, got, others, spec.get(field, normalized)),
"passes_validation": passes_validation(field, got),
}
def review_queue(reference, extracted, cells, spec=None, weights=None):
"""One row per value to review: wrong, invented, then missed. Heavier fields first."""
spec, weights = spec or {}, weights or {}
rows = [
review_row(reference, extracted, key, field, result, spec)
for key, record in cells.items()
for field, result in record.items()
if result in PRIORITY
]
rows.sort(
key=lambda r: (PRIORITY[r["outcome"]], -weights.get(r["field"], 1), r["field"], r["key"])
)
return rows
The type is a guess that sorts the queue, and a person decides. Here are the first rows for the made-up data, with price weighted heaviest:
queue = review_queue(reference, summary["extracted"], summary["cells"], spec, {"price": 3})
for row in queue[:7]:
shown = [row["key"], row["field"], row["reference"], row["extracted"]]
print(*shown, row["error_type"], row["passes_validation"], sep=" | ")
Output:
book-03 | price | 30.99 | 14.99 | adjacent_record | True
book-09 | price | 26.99 | 269.9 | decimal_shift | True
book-14 | price | 15.99 | £15.99 | extra_text | False
book-02 | in_stock | True | False | flipped | True
book-10 | in_stock | True | False | flipped | True
book-05 | rating | 1 | 2 | off_by_one | True
book-06 | title | Ash and Ember | Ash and | truncated | True
These are the incorrect but plausible values. Six of these seven pass validation: a price from the neighboring card, a price ten times too high, two flipped stock statuses, a rating one star out and a title cut short. All are well-formed, and a schema would accept every one. Only the price with a symbol left in fails. Here is one record in full, the page beside the extraction:
key = "book-03"
print("page: ", reference[key])
print("extracted:", summary["extracted"][key])
Output:
page: {'title': 'Paper Moons', 'price': 30.99, 'rating': 4, 'in_stock': True, 'discount_price': None}
extracted: {'title': 'Paper Moons', 'price': 14.99, 'rating': 4, 'in_stock': True, 'discount_price': None}
Nothing in the extracted record looks wrong until you hold it against the page.
Run the pipeline
Now the real extraction. Ask for the fields as a schema, allow each one to be null, and tell the extractor to use null when the page shows nothing. That keeps a missing value missing, so the suite counts it as missed and not as invented:
RECORD = {
"type": "object",
"properties": {
"key": {"type": ["string", "null"], "description": "the product's title or URL"},
"title": {"type": ["string", "null"]},
"price": {"type": ["number", "null"]},
"rating": {"type": ["integer", "null"], "description": "star rating from 1 to 5"},
"in_stock": {"type": ["boolean", "null"]},
},
}
SCHEMA = {"type": "object", "properties": {"books": {"type": "array", "items": RECORD}}}
PROMPT = (
"Extract every product on the page. Use null when the page does not show a value. Never guess."
)
def extract_page(client, url, schema, list_key="books", prompt=PROMPT):
"""One page in, (records, error) out. A page that fails is reported, never skipped."""
params = ScrapeParams(urls=[ScrapeUrl(url=url)], prompt=prompt, schema=schema)
try:
content = client.scrape(params).content
except SpidraError as error:
return [], str(error)
records = content.get(list_key) if isinstance(content, dict) else None
return (records, None) if isinstance(records, list) else ([], f"no {list_key!r} list came back")
def run_pipeline(client, urls, schema, out, list_key="books"):
"""Write one JSON line per record, with the page it came from. Returns {url: error}."""
failures = {}
with open(out, "w", encoding="utf-8") as handle:
for url in urls:
records, error = extract_page(client, url, schema, list_key)
failures.update({url: error} if error else {})
handle.writelines(
json.dumps({**record, "_page": url}, ensure_ascii=False) + "\n"
for record in records
)
return failures
A page that fails is returned as a failure and its records don't exist, so it lowers coverage instead of disappearing:
# needs SPIDRA_API_KEY
client = Spidra(api_key=os.environ["SPIDRA_API_KEY"])
urls = ["https://example.com/catalog?page=1", "https://example.com/catalog?page=2"]
failures = run_pipeline(client, urls, SCHEMA, "extracted.jsonl")
print(len(failures), "pages failed")
Then score it, and write the review sheet:
def write_review(path, rows):
with open(path, "w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=list(rows[0]) if rows else ["key"])
writer.writeheader()
writer.writerows(rows)
def build_parser():
ask = argparse.ArgumentParser(description="Score an extraction against a reference set.")
ask.add_argument("reference")
ask.add_argument("extracted")
ask.add_argument("--key", required=True)
ask.add_argument("--fields", required=True, help="comma-separated")
ask.add_argument("--match", action="append", default=[], help="field=rule[:argument]")
ask.add_argument("--review", help="write the values to review to this CSV")
return ask
def save_queue(path, reference, summary, spec):
queue = review_queue(reference, summary["extracted"], summary["cells"], spec)
write_review(path, queue)
print(f"\nWrote {len(queue)} values to review: {path}")
def main(argv=None):
args = build_parser().parse_args(argv)
fields = [f.strip() for f in args.fields.split(",") if f.strip()]
try:
spec = dict(parse_match(rule) for rule in args.match)
reference = load_reference(args.reference, args.key, fields)
summary = summarize(reference, read_rows(args.extracted), args.key, fields, spec)
except (ValueError, OSError) as error:
print(f"error: {error}", file=sys.stderr)
return 1
print(render(summary, fields))
return save_queue(args.review, reference, summary, spec) or 0 if args.review else 0
Save these pieces as evaluate.py and run python evaluate.py reference.csv extracted.jsonl --key key --fields title,price,rating,in_stock --match price=numeric:0.005 --match rating=integer --match in_stock=boolean --review review.csv. A bad reference set or an unknown rule prints one error: line and exits with 1.
How many pages you need
The interval tells you whether a sample is big enough. Suppose a field is 95% right:
def clean_pages_needed(target, z=1.96, limit=100000):
"""The fewest error-free cells whose interval's lower bound reaches the target."""
for n in range(1, limit):
if wilson(n, n, z)[0] >= target:
return n
return None
for n in (20, 50, 100, 300):
low, high = wilson(round(0.95 * n), n)
print(f"{n:>4} values, 95% right: the true accuracy is between {low:.0%} and {high:.0%}")
print("error-free values needed to show 95%:", clean_pages_needed(0.95))
Output:
20 values, 95% right: the true accuracy is between 76% and 99%
50 values, 95% right: the true accuracy is between 87% and 99%
100 values, 95% right: the true accuracy is between 89% and 98%
300 values, 95% right: the true accuracy is between 92% and 97%
error-free values needed to show 95%: 73
With 20 values, "95% right" could be 76% or 99%. To show 95% with no errors at all, you need 73 values. So decide what each field needs from the cost of an error, such as a price that's wrong or a stock status that's flipped, and ship a field only when the lower bound of its interval clears that target. Sample each page template separately.
What these metrics don't cover
Coverage, missing-field rate and accuracy say nothing about freshness, how stable a run is from one day to the next, or whether the reference is itself correct. Duplicates are reported, but not scored. Pages change, so re-label a sample on a schedule, and keep the agreement numbers, because a reference set is only as good as its labelers.
For the checks on shape that run before you measure, see these posts on validating scraped JSON and normalizing prices.
Wrapping up
Whether the data comes from your own scripts or from a vendor, six questions decide if you can rely on it:
- What is the reference set, who labeled it, and how closely did they agree?
- What is the denominator of every rate?
- Are missing and wrong values counted apart?
- What is the score for each field, with its interval?
- What do the wrong values look like?
- Was it measured on pages like yours?
An accuracy figure that can't answer them isn't a measurement. The accuracy and cost-per-record numbers we publish use the definitions in this post unchanged, so they're comparable.
This is where Spidra helps you run the test. Create a free account, label 30 of your own pages, run run_pipeline on them, and read the three numbers.
Top comments (0)