Web Scraping for Machine Learning: Build the Dataset Right
Build a web scraping for machine learning pipeline that turns 320 crawled pages into validated, deduplicated training data. Real commands and real numbers.

On this page
Nobody publishes the dataset you actually need. So you scrape one, and the model you train next week is only as good as the boring decisions you make before any modeling happens. This is a working web scraping for machine learning pipeline: one crawl turned 320 book pages into 268 validated, labeled records, and the first classifier trains on them in 1.4 seconds. Every command and number below comes from that run.
Where web scraping for machine learning ends and ML begins
Magpie (a free Go CLI, AGPL-3.0 or commercial) does the acquisition half: it fetches pages politely, strips boilerplate, and pushes each page through a JSON Schema so you get the typed records that make scraped data AI-ready instead of a folder of HTML. In this run it also exposed the single biggest dataset bug, but I’m getting ahead of the story.
Magpie does not build datasets. There is no dedupe button, no train/test split, no label validation, no exporter to scikit-learn. Analysis, deduplication, and modeling happen in your own code, and that is the correct division of labor: cleaning rules are product decisions, and you will change your mind about them. Anything a vendor sells you as “auto-curated training data” is making those decisions invisibly.
So the honest shape of web scraping for machine learning is: the crawler gets records, your code makes them a dataset. This page wires both halves together.
Before you start
- Magpie v0.1.32 installed (
go install github.com/motherlodelab/magpie@latestor grab a release), with an LLM key for schema extraction. This run used OpenRouter withgpt-4o-mini. - Python 3.12 with
scikit-learn1.9.1 andpandas3.0.6 (pip install scikit-learn pandas). - A target you’re allowed to scrape. I used books.toscrape.com, a sandbox built for exactly this: 1,000 fake book pages, no robots.txt, “We love being scraped!” in the footer. For real targets, read the legality piece first: scraping for AI training has its own case law and its own GDPR wrinkles.
- Ten minutes of schema thinking and, later, patience: the crawl took 28 minutes.
One check before any crawl: search whether the dataset already exists. Hugging Face alone hosts hundreds of thousands of sets, and a published one beats a scraped one on provenance every time. Scrape when your label space, your language, or your niche is not covered.
Step 1: Write the schema before the crawler runs
The schema is your dataset contract. It defines one record, so write it like a data engineer, not a prompt hacker: short field names, typed values, a natural key.
{
"name": "book_product",
"type": "object",
"properties": {
"title": { "type": "string", "description": "Book title as shown in the page H1" },
"category": { "type": "string", "description": "The middle breadcrumb value between 'Books' and the title, e.g. 'Poetry'" },
"description": { "type": "string", "description": "The Product Description paragraph text, verbatim" },
"price_gbp": { "type": "number", "description": "Price including tax, without the currency symbol" },
"upc": { "type": "string", "description": "The UPC from the Product Information table" }
},
"required": ["title", "category", "description", "upc"]
}
Two choices matter more than they look. The UPC is a natural key: when the same product reaches you twice, you can prove it. And the category comes from the breadcrumb, which is the site’s own taxonomy. Never let an extractor invent labels from the text; your label space should be the site’s, or you’re building two datasets and only charging yourself for one.
Step 2: Crawl pages into records
magpie crawl "https://books.toscrape.com/catalogue/page-1.html" \
--no-sitemap --max-depth 16 --max-pages 320 \
--include '**/catalogue/*_*/index.html,**/catalogue/page-*.html' \
--schema book-schema.json \
--provider openrouter --model openai/gpt-4o-mini \
--rate 2 --format jsonl --out books-raw.jsonl --max-cost 0.50
The include globs do real work here. Every page on this site links to all 50 category indexes, so an unconstrained crawl spends its page budget on near-empty listing pages. The first glob admits product pages, the second lets the crawler follow the paginated catalog, and 28 minutes later the run line reads:
crawl: run_id=168a849533186822-193792 pages_ok=320 pages_err=0 records=320
320 pages fetched, 0 errors, 320 JSONL records. Cost: Magpie doesn’t print a meter for crawls, so this is an estimate from token math — roughly 1,500 input plus 200 output tokens per page at gpt-4o-mini prices ($0.15/$0.60 per million) is about ten cents for the whole run.
Watch the warnings in the log:
warning: selector: field "category" agrees on 2/3; caching anyway
warning: selector: fields [category description price_gbp] below agreement threshold; per-page LLM extraction (not cached)
So what are those warnings? Magpie cross-checks LLM extraction against a cached CSS selector and only keeps the selector when sampled pages agree; fields below the threshold stay on per-page LLM extraction. That mechanism is why the next step exists: a selector that “agrees on 2/3” got cached, and it was reading the wrong breadcrumb node. If you’d rather pay for per-page simplicity instead, Magpie’s own AI web scraper takes plain-English prompts in place of a schema.
Step 3: Enforce the record contract in code
The crawler emits a record per fetched page, including the six listing pages the globs admit. Those pages have no UPC, so the extractor helpfully hallucinated one: page 2 got "upc": "980". A record contract catches that in one line.
import json, re
import pandas as pd
product = re.compile(r"^https://books\.toscrape\.com/catalogue/[^/]+/index\.html$")
rows = []
for line in open("books-raw.jsonl"):
r = json.loads(line); ex = r.get("extracted") or {}
if product.match(r["url"]) and re.fullmatch(r"[0-9a-f]{16}", str(ex.get("upc") or "")):
rows.append(ex | {"url": r["url"]})
df = pd.DataFrame(rows)
314 of 320 records pass. The six failures are the listing pages, each with a fabricated two- or three-digit UPC. Real UPCs here are 16 hex characters; that check, plus the URL shape, is the whole contract. Write it before you look at the data, because you will rationalize anything after.
Step 4: Dedupe on the natural key before splitting
dupes = df[df.duplicated("upc", keep=False)] # 0 rows this run
df = df.drop_duplicates("upc")
Zero duplicates here, for two reasons worth knowing: the crawler’s visited-set already refuses the same URL twice, and this dataset has a single source. The check still ships, because the first time you merge two crawls or extend one across a week, duplicates will appear — and a duplicate that straddles your train/test split inflates every metric you own. Dedupe first, split second. This ordering is the single most common self-inflicted wound in scraped datasets.
Step 5: Validate labels against a second extraction
Then the big one. 123 records came back with the category Books, Add a comment, or Default. The cached breadcrumb selector had learned to read the literal “Books” node, and on some pages it grabbed a comment-form heading. That is 39% of the dataset carrying a broken label, and nothing about the records looks wrong at a glance.
The fix is a principle: never accept a label from a single extractor. The site’s own breadcrumb is an independent signal, so re-fetch the suspect pages as raw HTML (Magpie’s --page-format raw returns the response body untouched) and parse the breadcrumb deterministically:
while IFS= read -r u; do
magpie scrape "$u" --page-format raw > "raw/$(echo "$u" | md5sum | cut -c1-12).html"
sleep 0.5
done < suspect-urls.txt
def breadcrumb_category(html):
m = re.search(r'<ul class="breadcrumb">(.*?)</ul>', html, re.S)
if not m: return None
texts = [re.sub(r"<[^>]+>", "", li).strip()
for li in re.findall(r"<li[^>]*>(.*?)</li>", m.group(1), re.S)]
texts = [t for t in texts if t and t != "Home"]
return texts[-2] if len(texts) >= 3 and texts[0] == "Books" else None
On the 122 suspect pages my loop actually fetched (my URL list lost one line to a missing trailing newline; every pipeline stage should log its counts), the breadcrumb parse disagreed with the extractor 117 times and agreed 4. I adopted the breadcrumb’s category on 103 rows, where it named a real leaf such as Poetry or Business; the other 14 disagreements pointed at the site’s junk “Default” leaf. Twenty rows kept no usable label from either pass, which leaves 294. Dropping beats guessing: a wrong label costs more than a missing row.
Step 6: Fix what the source itself breaks
This site repeats its own product blurb inside the description; the text just starts over mid-sentence. 99 of the 294 surviving records had it. A fixed description field poisons a text classifier with phase-shifted duplicates, so normalize at load:
def dedupe_blurb(text):
sents = re.split(r"(?<=[.!?]) +", text)
for n in (3, 2):
if len(sents) >= 2 * n:
head = " ".join(sents[:n])
i = text.find(head, len(head))
if i > 0:
return text[:i].rstrip(" ,;")
return text
df["description"] = (df["description"].map(dedupe_blurb)
.str.replace(r"\s*\.\.\.more$", "", regex=True)
.str.replace(r"\s+", " ", regex=True).str.strip())
df = df[df["description"].str.len() >= 120] # drops 3 stub descriptions
The ...more suffix is the site’s truncation widget; three more records are stubs shorter than the model can learn from, which leaves 291 rows. Both quirks are invisible until you go looking, which is the point: read twenty records by hand before you trust any of them. If your source is messier than a demo site, the deeper cleaning patterns live in the data-cleaning guide.
Step 7: Split, train, then distrust the score
291 rows across 39 categories, with counts per category running from 1 to 20. Stratified splits and per-class metrics turn to noise below about 4 examples, so a minimum-samples rule applies: categories with fewer than 4 go. 25 categories survive, 23 rows leave, and the dataset is final: 268 rows, 5 to 20 examples per class.
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
train, test = train_test_split(df, test_size=0.25,
stratify=df["category"], random_state=42)
model = Pipeline([
("tfidf", TfidfVectorizer(ngram_range=(1, 2), min_df=2, sublinear_tf=True)),
("lr", LogisticRegression(max_iter=2000, class_weight="balanced")),
]).fit(train["description"], train["category"])
Scores, honestly: the held-out test set (67 rows) lands at 32.8% accuracy, macro-F1 0.294. Five-fold cross-validation across the full dataset runs 36.2% ± 6.0%. Before you wince: this is a 25-way problem, so random guessing sits at 4%. And the model reads real signal: its strongest features for Poetry are “poetry, collection, of poetry”, for Science “universe, physics”, for Business “startup, advice, entrepreneurs”. Labels are sound; the ceiling is sample count.
I can prove that from the same data, because the class sizes vary:
| Label floor | Classes | Rows | 5-fold accuracy |
|---|---|---|---|
| ≥ 5 per class | 25 | 268 | 36.2% ± 6.0% |
| ≥ 8 per class | 18 | 227 | 39.2% ± 5.5% |
| ≥ 12 per class | 9 | 139 | 59.0% ± 4.6% |
| ≥ 20 per class | 2 | 40 | 85.0% ± 12.2% |
Same model, same features. The only variable is examples per class, and accuracy climbs nearly 50 points as the floor rises from 5 to 20. When a scraped-data model disappoints, the fix is almost never hyperparameters; it is another twenty pages of catalog. This is also why the site’s class table matters more than the confusion matrix: it tells you the accuracy you can afford before you train anything. (For the analysis-flavored cousin of this pipeline, dashboards instead of classifiers, see the data-analysis guide.)
Make it stick
Refresh, don’t restart. The crawl is checkpointed, so magpie crawl --resume 168a849533186822-193792 picks up where the page budget stopped: 101 frontier URLs were still pending when this run capped out, another catalog’s worth of per-class headroom. Re-run the pipeline script over the merged output; the contract, dedupe, and label checks all re-execute, and that is the actual safety net when a site redesign lands mid-project.
Then write the datasheet while the run is fresh. Ten lines, no format religion:
source: books.toscrape.com (demo sandbox, no robots.txt)
collected: 2026-10-17
method: magpie crawl v0.1.32, gpt-4o-mini schema extraction
size: 268 records, 25 classes, 5-20 examples per class
fields: title, category, description, price_gbp, upc
cleaning: 6 off-contract rows dropped; 99 in-record duplicated blurbs fixed; 3 stubs dropped
labels: 123 rows re-validated against page breadcrumbs; 103 repaired, 20 dropped
splits: train 201 / test 67, stratified, seed 42
score: 36.2% +/- 6.0% 5-fold accuracy (25-way; chance 4%)
known gap: English-language blurbs only; prices are fiction
Six months from now, that file is the only thing that tells your successor (or you) whether the model can be retrained or has to be rebuilt.
FAQ
Is web scraping legal for training machine-learning models? Depends on jurisdiction, source, and use. US case law (hiQ v. LinkedIn) has favored scraping public data, but the EU treats personal data under GDPR regardless. Contracts matter: terms of service can prohibit it, and lawsuit risk is real. Read the full treatment before betting a project on it.
How much data do I need before training? For classical models on text, dozens per class to start, hundreds to be comfortable. This run’s own curve: 5 per class scored 36%, 20 per class scored 85% on the easiest split. Measure your label distribution first; it predicts the score.
Should I deduplicate before or after the train/test split? Before. A duplicate in both train and test makes the model look like it memorized nothing while it memorized everything. Dedupe on a natural key (UPC, hash of normalized text), then split, then never touch the test set again.
Can an LLM label my scraped data instead of me? For extraction against a fixed schema, yes; that’s what this pipeline does. For open-ended labeling, an LLM will happily invent plausible categories you never defined. Keep the label space closed, and validate a sample against a second source the way Step 6 does.
What happens when the site changes mid-project?
Your validation layer tells you first: record counts shift, contract checks fail, label distributions drift. Re-run the crawl with --resume, re-run the pipeline unchanged. If extraction breaks structurally, the schema is the single file to fix.
The next concrete move
Point this pipeline at one real catalog you care about tonight — 50 pages, one schema, one datasheet. The model will be mediocre and the numbers will be honest, which puts you ahead of every “500 million labeled examples” marketing page on the internet.


