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"Source:https://dev.to/oyedeletemitope/how-to-measure-scraping-data-quality-1045Related posts
Best Red-Light Therapy for Hair Growth and Restoration (2026)
How to Protect Against *2Shell Vulnerabilities: Honeytokens, WAF Blocks and Patches That Prove Themselves
EC2 Capacity Blocks for ML: One Search Across Instance Types and Regions
I Tried Building a Tutor Marketplace. Here's What Made the Backend Complicated
