# How to validate scraped data with checks you can count | Spider

Five checks run over one 20-page crawl of a practice book shop, how many rows each one passed or flagged, and what a flag tells you about a row.

Canonical: https://spider.cloud/learn/data-checks/

To validate scraped data, give every row plain rules to pass, such as a 200 status, some text, an address no other row shares, a sensible size and the field you came for, then count the rows that fail each rule before anything reads them. A count of zero is a result too, because it shows the check ran, which a pipeline that only logs failures never tells you.

This page runs five such checks over one 20-page crawl of a practice shop and prints the count for each one. The one count that is not zero points at two short pages, and the text the run printed for them hints at a reason other than a fault. That is the second half of the lesson. A check marks a row for a look, and a person or a sharper rule decides what the mark means.

In a [web scraping](/web-scraping/) job these checks belong after the fetch and before the save, so a bad page is caught while it is still a page and not yet a record in your file.

## What each check catches

| Check                        | What it catches                            | The rule in the program                      |
| ---------------------------- | ------------------------------------------ | -------------------------------------------- |
| Status not 200               | An error page saved as if it were content  | `status` is anything but 200                 |
| Empty content                | A page that answered with no text          | the text is blank once whitespace is trimmed |
| Duplicate url                | The same address fetched twice             | the url string appears on more than one row  |
| Content under 1 KB           | A stub, a page of navigation, a short read | fewer than 1,024 bytes of UTF-8              |
| No price line on a book page | A product page your extractor cannot use   | a book's own page with no line like `£51.33` |

The status check comes first because the others mean little without it. RFC 9110 defines the code this way: "The 200 (OK) status code indicates that the request has succeeded." This exercise wants every page whole, so it expects a 200 and flags anything else for review. A flag here is not always a failure. A 404 body is the server's notice about a missing page, a redirect points somewhere else, and a 206 carries only part of the page, so none of them should be saved as the page you asked for until someone has looked. The [status codes page](/learn/http-status-codes/) covers what each family means and which ones are worth a retry.

Empty content gets its own check because a 200 can carry nothing. The status line and the body are separate, and a row can pass one and fail the other.

The duplicate check needs a choice of column. The pandas documentation describes the `subset` argument of `DataFrame.duplicated` as a way to "Only consider certain columns for identifying duplicates", and in a crawl the column that matters is the address. The program below does the same thing with a counter over the url strings. Comparing strings has a blind spot, which comes up again after the counts.

The size floor is a guess you should test. The idea behind one kilobyte is that a product page clears it and a page holding only a header and a menu does not. Whether that holds on a given site is for a run to show.

The last check is the one closest to the data you want. It applies to pages that should carry a price, so the program first decides whether a url is a book's own page, then looks for a line that is a pound sign and a number with two decimals. On a real job you would pull the price with a selector instead, and [XPath vs CSS selectors](/learn/xpath-vs-css/) shows both ways of writing one for this same shop.

This clip counts what each of the five checks flagged, then opens the two flagged rows.

Count what each check flagged. 53 s, no sound. The words are on screen, and the captions button shows them at your own text size.

Read the transcript

Count what each check flagged. Five checks run on the 20 rows of one crawl of a practice shop.

Four checks flagged nothing. One flagged 2 of the 20 rows. 18 rows passed every check. 2 rows flagged by content under 1 KB. 5: checks, each with its own count. 4: checks that flagged nothing. 2: rows to open and read.

Both flagged pages are short because each lists 1 book. content under 1 KB flagged 2 of 20 rows. parenting_28: 674 bytes. short-stories_45: 501 bytes. each page says: 1 result. 1024: bytes, the floor the check sets. 18: rows cleared it.

The price check ran only on the 9 book pages. All 9 passed. no price line on a book page: rows in the run 20, rows the check ran on 9, passed 9, flagged 0. 11: rows it left alone.

A flag is a lead. Open the row and read it before you drop it. After the counts: any row flagged?. clean: Use the rows. flagged: Open each flagged row and read it. This run: flagged.

Read the full page. The page is at spider.cloud/learn/data-checks.

## The run

One `/crawl` request fetches the pages, and the checks run over the response before anything is saved. The body starts at the shop's home page with `limit` set to 20, asks for markdown so each price lands on its own line, sets `delay` to 1000 milliseconds and sends a user agent with a contact address. For each flagged row the program also prints any line of that row's text that gives a result count or a price. That way you can judge the flag from the response you already have. The key comes from `SPIDER_API_KEY`. The standard library is enough, but `str.removeprefix` needs Python 3.9 or later. Save the file as `data_checks.py`.

```python
"""Crawl 20 pages of a practice catalogue through the Spider API, keep the
url, status and content size of each page, and count the rows that fail
five checks.

    python3 data_checks.py
"""
import json
import os
import re
import sys
import urllib.request
from collections import Counter

API = "https://api.spider.cloud/crawl"
START = "https://books.toscrape.com/"
SITE = "https://books.toscrape.com"
PRICE = re.compile(r"^£\d+\.\d\d$", re.M)
# A book's own page: /catalogue/<slug>_<id>/index.html. Category and listing pages differ.
BOOK = re.compile(r"/catalogue/[^/]+_\d+/index\.html$")
# Lines printed under a flagged row, so you can judge it without a second fetch.
EVIDENCE = re.compile(r"results?\.$|^£\d+\.\d\d$")


def is_book(url):
    return bool(BOOK.search(url))


def main() -> int:
    key = os.environ.get("SPIDER_API_KEY")
    if not key:
        print("set SPIDER_API_KEY first")
        return 1
    body = json.dumps({
        "url": START,
        "limit": 20,
        "request": "http",
        "return_format": "markdown",
        "delay": 1000,
        "user_agent": "examplebot/1.0 (+https://example.com/bot; bot@example.com)",
    }).encode()
    req = urllib.request.Request(API, data=body, headers={
        "Authorization": f"Bearer {key}",
        "Content-Type": "application/json",
    })
    with urllib.request.urlopen(req, timeout=300) as resp:
        pages = json.load(resp)

    rows = []
    for p in pages:
        text = p.get("content") or ""
        rows.append({
            "url": p.get("url") or "",
            "status": p.get("status"),
            "bytes": len(text.encode("utf-8")),
            "text": text,
        })

    seen = Counter(r["url"] for r in rows)
    checks = [
        ("status not 200", lambda r: True, lambda r: r["status"] != 200),
        ("empty content", lambda r: True, lambda r: not r["text"].strip()),
        ("duplicate url", lambda r: True, lambda r: seen[r["url"]] > 1),
        ("content under 1 KB", lambda r: True, lambda r: r["bytes"] < 1024),
        ("no price line on a book page", lambda r: is_book(r["url"]),
         lambda r: not PRICE.search(r["text"])),
    ]

    print(f"rows {len(rows)}")
    for r in rows:
        print(f"{r['status']}  {r['bytes']:>6}  {r['url'].removeprefix(SITE)}")
    print()
    for name, applies, fails in checks:
        scope = [r for r in rows if applies(r)]
        flagged = [r for r in scope if fails(r)]
        print(f"{name:<29} checked {len(scope):>2}  passed {len(scope) - len(flagged):>2}  flagged {len(flagged)}")
        for r in flagged:
            print(f"    {r['bytes']:>5}  {r['url'].removeprefix(SITE)}")
            for line in r["text"].splitlines():
                if EVIDENCE.search(line.strip()):
                    print(f"           {line.strip()}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
```

This is the whole output of the program above, run once on 2026-11-21 at 21:12:51 UTC on Python 3.14.7. The sizes are measured from the full markdown in that one response. Each row gives the status, the size of the page's markdown in bytes and the path. The tally under the rows gives each check's own count, and the indented lines under a flagged row are copied from that row's text in the same response.

```text
rows 20
200    6250  /
200    5357  /catalogue/category/books/science-fiction_16/index.html
200    4014  /catalogue/its-only-the-himalayas_981/index.html
200    3755  /catalogue/scott-pilgrims-precious-little-life-scott-pilgrim-1_987/index.html
200    1953  /catalogue/category/books/christian-fiction_34/index.html
200    5906  /catalogue/category/books/childrens_11/index.html
200    1420  /catalogue/category/books/politics_48/index.html
200     674  /catalogue/category/books/parenting_28/index.html
200    2313  /catalogue/soumission_998/index.html
200    1730  /catalogue/category/books/health_47/index.html
200    2919  /catalogue/the-requiem-red_995/index.html
200    3795  /catalogue/libertarianism-for-beginners_982/index.html
200    4035  /catalogue/starving-hearts-triangular-trade-trilogy-1_990/index.html
200    3631  /catalogue/shakespeares-sonnets_989/index.html
200    4305  /catalogue/mesaerion-the-best-science-fiction-stories-1800-1849_983/index.html
200    6110  /catalogue/category/books/historical-fiction_4/index.html
200    8076  /catalogue/category/books/nonfiction_13/index.html
200    2530  /catalogue/category/books/art_25/index.html
200    4141  /catalogue/the-dirty-little-secrets-of-getting-your-dream-job_994/index.html
200     501  /catalogue/category/books/short-stories_45/index.html

status not 200                checked 20  passed 20  flagged 0
empty content                 checked 20  passed 20  flagged 0
duplicate url                 checked 20  passed 20  flagged 0
content under 1 KB            checked 20  passed 18  flagged 2
      674  /catalogue/category/books/parenting_28/index.html
           **1** result.
           £37.35
      501  /catalogue/category/books/short-stories_45/index.html
           **1** result.
           £35.88
no price line on a book page  checked  9  passed  9  flagged 0
```

## Reading the counts

Four of the five checks flagged nothing. All 20 statuses were 200, no page came back empty and no address string appeared twice. Nine of the rows were a book's own page, and each of the nine had a price line.

The size check flagged two rows, the parenting and short stories categories, at 674 and 501 bytes. The lines printed under each come from its own text: the page says `**1** result.` and shows one price. A category that lists a single book could well be short for that reason alone. That is a lead, not a finding. The run printed only those lines, not the rest of either page, so both flags stay open until someone opens the two rows and reads them.

What the run does show is that the floor fits book pages better than category pages. The nine book pages ran from 2,313 to 4,305 bytes, well clear of 1 KB, while the category sizes spread from 501 to 8,076. A floor per page type, set from pages you have opened and read, fits that spread better than one lower number for the whole site.

The duplicate check passed, but it compares strings, and two strings can name one page. If a crawl returned both `/` and `/index.html`, the check would pass both rows. To catch that case, compare a hash of each page's text as well as its address, and read both rows when the hashes match.

The price check has a limit of its own. The shop's home page carries a banner saying "Prices and ratings here were randomly assigned and have no real meaning." The check confirmed that every book page had something shaped like a price. It cannot say whether the price is right, and no pattern can. That takes a second source to compare against.

## Do this, avoid this

### Do this

- Print a passed and a flagged count for every check on every run, including the checks that flag nothing.
- Set the size floor per page type, from pages you have opened and read.
- Run the field check only on pages that should carry the field, and test the page-type rule on a listing page first.
- Hash each page's text and compare the hashes as well as the addresses.
- Store each run's counts with its date and request body.

### Avoid this

- Deleting a flagged row before anyone has opened it.
- Reading a price that matches a pattern as a correct price.
- Logging a flag with only its address, so that judging it takes a second fetch.
- Publishing product descriptions you scraped without finding out who holds the copyright.

The request keeps `delay` at 1000, a one-second pause between requests, which suits a sandbox like this one. The [request rate page](/learn/request-rate/) covers how to pick a pace for a real site. Books to Scrape was built for practice. Before you run the same checks against a live shop, read its [robots.txt](/learn/robots-txt/) and its terms.

To point the program at another site, change `START`, `SITE`, the `BOOK` pattern and the price pattern, run it once and open every flagged row before you trust the counts. On this shop the run gave two flags, both on categories that report one result. If reading them confirms that, the next change is the size rule rather than the crawl.

## Sources

1. [RFC 9110, HTTP Semantics, IETF, June 2022](https://www.rfc-editor.org/rfc/rfc9110.html) Read November 21, 2026
2. [pandas documentation, DataFrame.duplicated](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.duplicated.html) Read November 21, 2026
3. [Books to Scrape, the home page of the practice shop](https://books.toscrape.com/) Read November 21, 2026
