Web Scraping for Data Analysis: From Raw Pages to Insights
A web scraping for data analysis pipeline, run end to end: crawl 1,000 listings to a corpus, parse rows, run pandas stats, see what cleaning deletes.

On this page
Web scraping for data analysis is mostly not scraping. I pointed a crawler at 50 listing pages on a bookstore sandbox, got 1,000 clean rows, and the actual answer, a groupby plus a correlation, took under two minutes of pandas. What usually goes wrong happens in the joints between the two halves, so this walkthrough runs the whole pipeline with real numbers at every step.
What web scraping for data analysis looks like end to end
Four stages, and each one has exactly one job:
| Stage | Job | Tool in this guide |
|---|---|---|
| 1. Question | Name the output: which columns, which comparison | you |
| 2. Corpus | Fetch and clean the pages, polite and resumable | Magpie crawl |
| 3. Rows | Turn records into a table with stable keys | Python + regex |
| 4. Answers | Stats, checks, charts | pandas (or your tool) |
One boundary to state up front, because most tooling marketing won’t: Magpie’s job ends at stage 2. It fetches, cleans, and structures. It does not dedupe, compute, chart, or model: that work belongs to pandas, R, or whatever your team already uses. This guide treats that split as the design, not a gap: you’ll see exactly where the scraper stops and the analysis starts, including one field the cleaner deletes on purpose and what to do about it.
Before you start: the Magpie CLI (single static Go binary, free to run under AGPL/commercial dual licensing), Python 3 with pandas, and a target. The demo target is books.toscrape.com, a sandbox built for scraping practice. Its own banner warns that prices and ratings are randomly assigned. That’s a feature for pipeline work: when you already know the truth about the data, a correct pipeline should reproduce it, and a broken one can’t fool you into seeing patterns that aren’t there.
Step 1: Start from the question, not the site
The question for this run: do higher-rated books cost more?
That sentence decides everything downstream. It names the unit (a book),
the columns (price, rating), and the comparison (mean price per rating).
A listing page shows title, price, and stock as text; the star rating
exists only as a CSS class, star-rating Four, with no visible text.
Flag it now: columns that live in attributes survive scraping badly,
and Step 6 deals with the fallout.
If you can’t write the question and its columns down before scraping, you’re collecting, not analyzing. Collections feel productive and analyze badly.
Step 2: Crawl the listing pages into a corpus
Magpie’s crawl --corpus mode fetches pages and writes one JSONL record
per page (url, title, depth, markdown) with the boilerplate
already stripped, without a single LLM call or API key:
magpie crawl "https://books.toscrape.com/catalogue/page-1.html" \
--corpus --out catalog.jsonl \
--max-pages 50 --max-depth 60 \
--path-prefix "/catalogue/page-"
crawl: run_id=83260371806b4322-253029 pages_ok=50 pages_err=0 records=50
50 pages, 1,000 book entries, 52.6 seconds, zero errors, zero LLM cost. The defaults did the politeness work: 1 request/second per host, and the crawler respects robots.txt.
Two constraints in that command are load-bearing, and both come from a failed first attempt:
- Scope the path. My first run had no
--path-prefix. The crawler followed the sidebar’s 50 category links instead of pagination, which bought me 13 nearly-empty category indexes and 485 entries of which 18 were duplicates (a book appears on the all-products page and its category page). A mixed population poisons every number downstream. - Pagination burns depth. BFS depth counts hops, and a 50-page
“next” chain is 49 hops.
--max-depth 1stops after page 2. The60looks weird; it’s the honest number.
A record looks like this (abridged):
{"url": "https://books.toscrape.com/catalogue/page-1.html",
"title": "All products | Books to Scrape - Sandbox",
"depth": 0,
"markdown": "01. \n ### [A Light in the ...](https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html)\n £51.77\n In stock\n02. ..."}
Notice the title: A Light in the .... Cleaning truncates long link
text. The full title lives on the book’s detail page; the URL, which
survives intact, is the join key that matters.
Step 3: Parse records into rows
The corpus is text; analysis wants a table. A short regex loop turns each entry into a row: the URL from the heading link, the price from the pound-sign pattern:
import json, re
rows = []
for line in open("catalog.jsonl"):
md = json.loads(line)["markdown"]
for m in re.finditer(
r"### \[[^\]]*\]\((https://[^)]+)\)\s*\n\s*\n\s*£([\d.]+)", md
):
rows.append({"url": m.group(1), "price": float(m.group(2))})
json.dump(rows, open("books.json", "w"))
print(len(rows), "rows")
1000 rows
The regex looks brittle because markdown is brittle: change the cleaner’s list formatting and this pattern dies. That’s fine. The contract between scraping and analysis is the row schema (url, price), not the parser; when the site or the cleaner changes, you fix one function.
Corpus mode stays JSONL (the CSV and SQLite export flags
belong to the schema path), so if a spreadsheet is the destination, end
the parse script with df.to_csv("books.csv", index=False) and you’re
done. See
scrape a website to CSV or JSON
for the direct routes.
Step 4: Load, dedupe, and count nulls every time
import pandas as pd
df = pd.DataFrame(json.load(open("books.json")))
print(len(df), "rows |", df.url.duplicated().sum(), "dupes |",
df.isna().sum().sum(), "nulls")
1000 rows | 0 dupes | 0 nulls
Thirty seconds, and it’s the difference between an insight and an
embarrassment. On the unscoped crawl from Step 2 this exact check would
have printed 18 duplicates, and those books would have been double-counted
in every mean. Nulls tell you a column didn’t survive the pipeline; if
rating had shown up here with 1,000 nulls, the question from Step 1
would be dead and better to learn now than after the charts.
Step 5: Answer the question in pandas
print(df.price.describe().round(2))
print(df.rating.value_counts().sort_index())
print(df.groupby("rating").price.agg(["mean", "count"]).round(2))
print("corr(price, rating) =", round(df.price.corr(df.rating), 3))
Real output (verbatim, pandas 3.0.0):
count 1000.00
mean 35.07
std 14.45
min 10.00
25% 22.11
50% 35.98
75% 47.46
max 59.99
rating
1 226
2 196
3 203
4 179
5 196
mean count
rating
1 34.56 226
2 34.81 196
3 34.69 203
4 36.09 179
5 35.37 196
corr(price, rating) = 0.028
The verdict: flat. A drift of £0.81 in mean price across five rating tiers and a correlation of +0.028 is no relationship. And that’s the correct answer. The sandbox announces its prices are random, so the pipeline just recovered a known truth.
That’s the cheapest validation you will ever run: point a new pipeline at data whose answer you already know. Only after it reproduces the known truth does it earn a real target, where the same five lines output a finding instead of a sanity check.
Step 6: When cleaning deletes a field
The rating column in Step 5 didn’t come from the corpus. The corpus has no ratings at all.
Ratings on this site live in a CSS class. Cleaning strips presentation (classes, scripts, layout) because its output targets prose and LLM context, and for those jobs the classes are noise. This is the right default and the deep version lives in cleaning scraped data. But it means one of my four columns needed a different route.
Attempt 1: ask an LLM. Magpie’s schema extraction promise looks tempting here:
env -u MAGPIE_BASE_URL magpie extract page1.html \
--schema books.schema.json \
--provider openrouter --model deepseek/deepseek-chat-v3-0324
{"type": "object",
"properties": {"books": {"type": "array", "items": {"type": "object",
"properties": {
"title": {"type": "string"},
"price_gbp": {"type": "number"},
"rating": {"type": "integer", "minimum": 1, "maximum": 5},
"in_stock": {"type": "boolean"}},
"required": ["title", "price_gbp", "rating", "in_stock"]}}},
"required": ["books"]}
It returned 20 books. The prices held up: 17 verifiably correct, three
titles too truncated to join, zero wrong. The ratings did not. Fourteen
of 20 came back wrong, mostly as confident 1s where the site shows 2–5
stars. A second run returned nothing but 5s. And a controlled test, a
minimal HTML file containing one unmissable star-rating Four class,
came back with "rating": 2.
The mechanism: extract runs the page through the cleaner before the
model sees it, so the class is gone from the prompt. The schema says
rating is required, so the model fills the blank with a plausible
integer rather than admitting the field doesn’t exist. A missing value
became confident fake data, the single most dangerous artifact a data
pipeline can produce and the reason the schema-extraction workflow
(how-to here) belongs on
messy text, not on attributes.
Attempt 2: parse the raw HTML. Sixteen lines, deterministic, and it matches the star classes the site serves on all 1,000 books:
import re, requests
from urllib.parse import urljoin
WORDS = ["One", "Two", "Three", "Four", "Five"]
rating = {}
for i in range(1, 51):
html = requests.get(
f"https://books.toscrape.com/catalogue/page-{i}.html", timeout=30
).text
for art in re.findall(r'<article class="product_pod">.*?</article>',
html, re.S):
h = re.search(r'href="([^"]+)"\s+title="([^"]+)"', art)
r = re.search(r"star-rating (\w+)", art)
if h and r:
u = urljoin(f"https://books.toscrape.com/catalogue/page-{i}.html",
h.group(1))
rating[u] = WORDS.index(r.group(1)) + 1
Join on url and the dataset is complete. Note what happened
organizationally: Magpie fetched and cleaned 50 pages politely; the
attribute-level field came from plain code you own. That’s the honest
division of labor: a scraper that cleans for prose will not keep
class-encoded data, and no amount of prompting recovers what the prompt
never contained.
Where web scraping analysis goes wrong
Four failure modes, all caught above, all with receipts:
- Unscoped seeds mix populations. The sidebar-following crawl
produced duplicates and empty pages before any analysis ran. Scope
with
--path-prefixor--include, then let the dedupe check prove the scope held. - Pagination eats depth budgets. Each “next” click is one more
BFS hop. Budget
max-depthat (pages − 1) for a linear chain, or your crawl quietly stops early and your N is wrong. - Thin listing pages fight the single-page cleaner.
magpie scrapeon a catalogue page dies withquality blocked (empty)(the main-content extractor finds no prose in a wall of list items), while corpus mode carries the same page happily. When a page is mostly records, crawl it;scrapeis for documents. - Required fields get invented. An LLM asked for a rating it cannot see will print one anyway, as run-after-run evidence above shows. Verify extraction against a deterministic sample before you let structured output near a chart.
The general shape: scraping errors don’t look like errors. They look like data — plausible rows, plausible numbers, wrong. Every check in Steps 3–4 exists because of that.
What Magpie does and doesn’t do in this pipeline
Does: the entire stage-2 job: scoped, polite, resumable crawling to a clean per-page corpus with no LLM cost; schema extraction through any of seven providers when the data is in the text; a Desktop app over the same engine if you don’t live in a terminal.
Doesn’t: deduplicate, aggregate, correlate, visualize, or model. It also won’t recover attribute-encoded fields the cleaner stripped; that’s your parser’s job, as Step 6 shows.
If your pipeline’s center of gravity is the analysis rather than the collection, Magpie is the collection end and pandas (or polars, or R) stays the analysis end. Everything stage 2 produced here sits in a local file that never left my machine. The only per-call cost in the whole run was the LLM experiment, and what LLM scraping costs prices that path with real token counts.
FAQ
Is web scraping data analysis legal?
Scraping publicly available pages at polite rates, respecting robots.txt, is broadly accepted practice, but legality depends on your jurisdiction, the site’s terms, and what you do with the data. Check the site’s terms, keep request rates human, and get proper advice for commercial use; this is experience, not legal advice.
Do I need an LLM for data extraction and analysis?
No. In this pipeline, regex and pandas handled 1,000 of 1,000 rows free; the LLM added invented ratings and a per-call cost. LLMs earn their keep on messy prose (descriptions, reviews, free-text fields), not on structure that a deterministic parser can read. Schema-extraction thinking is covered in extracting structured data from text.
How do I analyze pages that need JavaScript?
A static-first fetch returns a JS shell for client-rendered pages, so
you need real browser rendering. Magpie escalates automatically when a
page needs it, and single-page scrape supports --render browser. The
same checks apply (dedupe, nulls, known-truth validation) regardless
of how the bytes arrived.
What format should scraped data be in before analysis?
One row per entity, one column per field, a stable join key (URLs work well), and a lossless format: CSV or JSONL. Never analyze the raw markdown directly: it mixes presentation with data, truncates link text, and changes shape when the site or cleaner changes.
Make it a time series
One crawl is a snapshot; the same command next week is a trend. Put the
crawl and the parse script in a directory, add a cron line, and write
each run’s books.json beside its date. When something shifts (prices,
stock, the site’s markup), the diff between two files tells you what,
when, and by how much, which is the analysis most people actually need.
If a page matters enough to watch between runs,
website change monitoring
turns that diff into a webhook.
And keep the known-truth habit: the sandbox pipeline that correctly reported “no relationship” is the one I’d trust on a real bookstore.


