protoneko's picture
Upload folder using huggingface_hub
61bb557 verified
|
Raw History Blame Contribute Delete
4.66 kB

Web Scraper — Book Catalogue

A production-style Python scraper for books.toscrape.com, a public e-commerce-style catalogue built specifically for scraping practice. It downloads the full 1,000-book catalogue across 50 paginated pages and writes a clean, typed CSV — and can optionally enrich each row by visiting the individual product page.

What it does

Field Source Notes
title h3 a[title] The visible text is truncated; the full title lives in the title attribute
upc listing card Optional; empty when the site omits it
price_gbp p.price_color £51.77 → 51.77 (float)
rating_1to5 star-rating classes ['star-rating','Three'] → 3
availability / num_available p.instock.availability text + parsed stock count
category product-page breadcrumb not on the listing — fetched per book with --detail
product_url h3 a[href] resolved to an absolute URL
scraped_at run time UTC ISO-8601

Real run on 2026-09-26: 1,000 books, 50 categories, ~1m43s end-to-end (including 1,000 detail-page fetches at 6 workers). The committed books.csv is the actual output of that run — not a sample.

Install

pip install -r requirements.txt

Run

# Catalogue only (fast, ~40s for all 50 pages)
python scraper.py books.csv

# Catalogue + per-product category enrichment (slower, ~2min)
python scraper.py books.csv --detail --workers 6

# Just look at the first 2 pages, with logging
python scraper.py sample.csv --max-pages 2 --verbose

Sample output (first rows of the real books.csv)

title,upc,price_gbp,rating_1to5,availability,num_available,category,product_url,scraped_at
A Light in the Attic,,51.77,3,In stock,0,Poetry,https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html,2026-09-26T09:42:40Z
Tipping the Velvet,,53.74,1,In stock,0,Historical Fiction,https://books.toscrape.com/catalogue/tipping-the-velvet_999/index.html,2026-09-26T09:42:40Z
Soumission,,50.1,1,In stock,0,Fiction,https://books.toscrape.com/catalogue/soumission_998/index.html,2026-09-26T09:42:40Z

Implementation details worth knowing

  • Retries with exponential backoff — fetch() retries on network errors and 5xx responses (4 attempts: 1.5s / 2.25s / 3.4s waits).
  • Encoding pitfall, fixed — the server sends Content-Type: text/html with no charset, so requests falls back to ISO-8859-1 and the £ sign becomes mojibake. fetch() pins resp.encoding = "utf-8" when the charset is missing or latin-1. This is the single most common silent bug in scrapers; it's handled explicitly.
  • Pagination is link-driven — it follows the li.next a href until it disappears, so adding/removing pages doesn't break the run.
  • Polite by default — a requests.Session reuses the TCP connection, a custom User-Agent is set, and there's a configurable delay between pages.

How I'd scale this

  • Rate limiting / politeness: move the fixed POLITE_DELAY to a token bucket so bursts are capped but throughput isn't needlessly throttled; honor Retry-After headers when the site returns 429.
  • Retries: swap the hand-rolled backoff for urllib3/tenacity with jitter (full-jitter avoids thundering-herd when many workers recover at once). For 4xx that are not 429 (e.g. 404), fail fast instead of retrying.
  • Concurrency: the catalogue pages are independent — parallelize the page fetch with the same thread pool already used for --detail. For larger jobs, fan out over an asyncio + httpx.AsyncClient worker pool.
  • Proxies / IP pools: when the target rate-limits per-IP, rotate a small set of residential/datacenter proxies per session and key your retry budget per-IP so a bad proxy doesn't poison the whole run.
  • Robustness: add a JSON-Schema or pandera validation step on the parsed rows before the CSV write, so a silent layout change fails loudly instead of shipping a half-populated file.
  • Persistence: for anything bigger than a few thousand rows, stream rows to SQLite/Parquet (or S3 + Parquet) instead of a single in-memory list, so a crash mid-run loses only the current page and the output is queryable.
  • Observability: log per-page row counts and a run manifest (URLs, timestamps, retries) — it's the first thing you need when a downstream dashboard shows a gap.

Files

  • scraper.py — the scraper (this is the deliverable)
  • books.csv — real output of a full run (1,000 rows)
  • requirements.txt — requests, beautifulsoup4
  • README.md — this file