""" scraper.py — Production-style web scraper for books.toscrape.com Scrapes the full book catalogue (title, price, rating, stock, availability, category, upc, URL) across all paginated result pages and writes the result to a CSV file. Design notes ------------ * `requests.Session` keeps a TCP connection alive across pages (faster + more polite than opening a new socket per page). * Retries with exponential backoff on network errors / 5xx responses. * A User-Agent is set (some sites block the default python-requests UA). * Pagination is driven by the "next" link, so the script works even if the site adds or removes pages. * Each parsed row is appended to a list and flushed to CSV once, so the output file is a single, consistent snapshot. Usage ----- python scraper.py [output.csv] [--max-pages N] [--verbose] Dependencies: requests, beautifulsoup4 (see requirements.txt) """ from __future__ import annotations import argparse import csv import sys import time from urllib.parse import urljoin from dataclasses import dataclass, asdict from pathlib import Path import requests from bs4 import BeautifulSoup BASE_URL = "https://books.toscrape.com" CATALOGUE_URL = f"{BASE_URL}/catalogue/page-1.html" REQUEST_TIMEOUT = 15 # seconds per HTTP request MAX_RETRIES = 4 # attempts per page BACKOFF_BASE = 1.5 # exponential backoff: 1.5s, 2.25s, 3.4s, ... POLITE_DELAY = 0.5 # pause between pages (seconds) FIELDS = [ "title", "upc", "price_gbp", "rating_1to5", "availability", "num_available", "category", "product_url", "scraped_at", ] @dataclass class Book: title: str = "" upc: str = "" price_gbp: float | None = None rating_1to5: int | None = None availability: str = "" num_available: int | None = None category: str = "" product_url: str = "" scraped_at: str = "" def build_session() -> requests.Session: s = requests.Session() s.headers.update({ "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/126.0 Safari/537.36 " "books-catalogue-scraper/1.0"), "Accept-Language": "en-GB,en;q=0.9", }) return s def fetch(session: requests.Session, url: str, verbose: bool = False) -> str: """GET a URL with retries + exponential backoff. Returns the body text.""" last_err: Exception | None = None for attempt in range(1, MAX_RETRIES + 1): try: resp = session.get(url, timeout=REQUEST_TIMEOUT) if resp.status_code >= 500: raise requests.HTTPError(f"server error {resp.status_code}") resp.raise_for_status() # The site sends `Content-Type: text/html` with no charset, so # requests falls back to ISO-8859-1 and mangles the "£" sign. # Pin UTF-8 (the charset the server actually uses). if not resp.encoding or resp.encoding.lower() == "iso-8859-1": resp.encoding = "utf-8" if verbose: print(f" [page] {url} -> {resp.status_code} " f"({len(resp.content)} bytes, attempt {attempt})") return resp.text except (requests.RequestException, ValueError) as err: last_err = err if attempt == MAX_RETRIES: break wait = BACKOFF_BASE ** attempt if verbose: print(f" [retry] attempt {attempt} failed ({err}); " f"sleeping {wait:.2f}s") time.sleep(wait) raise RuntimeError(f"giving up on {url} after {MAX_RETRIES} attempts: {last_err}") def parse_price(raw: str) -> float | None: """'£51.77' -> 51.77 ; returns None when unparseable.""" if not raw: return None try: return float(raw.replace("£", "").replace(",", "").strip()) except ValueError: return None def parse_stock(raw: str) -> int | None: """'In stock (21 available)' -> 21 ; 0 when 'In stock' with no number.""" if not raw or raw.strip().lower().startswith("out of stock"): return 0 digits = "".join(ch for ch in raw if ch.isdigit()) return int(digits) if digits else 0 def parse_rating(class_names: list[str]) -> int | None: """Star rating classes look like ['star-rating','Three'].""" for cls in class_names: word = cls.split()[-1].capitalize() mapping = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5} if word in mapping: return mapping[word] return None def parse_catalogue_page(html: str, scraped_at: str, page_url: str = BASE_URL) -> list[Book]: soup = BeautifulSoup(html, "html.parser") books: list[Book] = [] for card in soup.select("article.product_pod"): title_el = card.select_one("h3 a") price_el = card.select_one("p.price_color") rating_el = card.select_one("p.star-rating") upc_el = card.select_one("table th") stock_el = card.select_one("p.instock.availability") category_el = card.select_one("div.product_type") title = "" if title_el is not None: # The visible text is truncated ("A Light in the ..."); # the full title lives in the title="" attribute. title = title_el.get("title") or title_el.get_text(strip=True) book = Book( title=title, product_url=(title_el.get("href", "").strip() if title_el else ""), price_gbp=parse_price(price_el.get_text(strip=True) if price_el else ""), rating_1to5=parse_rating(list(rating_el["class"])) if rating_el and "class" in rating_el.attrs else None, availability=(stock_el.get_text(strip=True) if stock_el else "unknown"), num_available=parse_stock(stock_el.get_text(strip=True) if stock_el else ""), category=(category_el.get_text(strip=True) if category_el else ""), scraped_at=scraped_at, ) if upc_el: book.upc = upc_el.get_text(strip=True) if book.product_url: book.product_url = urljoin(page_url, book.product_url) books.append(book) return books def find_next_url(html: str, page_url: str = BASE_URL) -> str | None: """Return the absolute URL of the 'next page' link, or None.""" soup = BeautifulSoup(html, "html.parser") next_el = soup.select_one("li.next a") if next_el and next_el.get("href"): return urljoin(page_url, next_el["href"].strip()) return None def parse_product_category(html: str) -> str: """Extract the book category from a product page breadcrumb. Breadcrumbs look like: Home > Books > Poetry (active = book title). The category is the last
  • that is *not* the active title and not 'Home'. """ soup = BeautifulSoup(html, "html.parser") items = soup.select("ul.breadcrumb li") category = "" for item in items: if "active" in item.get("class", []): break label = item.get_text(strip=True) if label and label.lower() != "home": category = label return category def enrich_with_details(books: list[Book], workers: int = 4, verbose: bool = False) -> int: """Fetch each product page and fill in the category field. The catalogue listing does not carry the category; the product page does (breadcrumb). Uses a small thread pool — requests are I/O-bound, so a few concurrent workers are fine and keep total runtime short. Returns the number of books whose category was filled. """ import concurrent.futures as cf session = build_session() def _fetch_one(book: Book) -> str: try: html = fetch(session, book.product_url, verbose=False) return parse_product_category(html) except RuntimeError as err: if verbose: print(f" [detail] {book.product_url}: {err}") return book.category filled = 0 with cf.ThreadPoolExecutor(max_workers=workers) as pool: for book, category in zip(books, pool.map(_fetch_one, books)): if category and category != book.category: book.category = category filled += 1 return filled def scrape_all(max_pages: int | None = None, verbose: bool = False) -> list[Book]: session = build_session() all_books: list[Book] = [] url: str | None = CATALOGUE_URL page = 0 while url is not None: page += 1 if max_pages is not None and page > max_pages: if verbose: print(f"[stop] reached --max-pages {max_pages}") break if verbose: print(f"[page {page}] fetching {url}") html = fetch(session, url, verbose=verbose) scraped_at = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) books = parse_catalogue_page(html, scraped_at, page_url=url) if verbose: print(f"[page {page}] parsed {len(books)} books") all_books.extend(books) url = find_next_url(html, page_url=url) if url and POLITE_DELAY: time.sleep(POLITE_DELAY) # De-duplicate on UPC (guards against accidentally re-visited pages). seen: set[str] = set() unique: list[Book] = [] for b in all_books: key = b.upc or b.product_url if key and key not in seen: seen.add(key) unique.append(b) return unique def write_csv(books: list[Book], path: Path) -> None: with path.open("w", newline="", encoding="utf-8") as fh: writer = csv.DictWriter(fh, fieldnames=FIELDS) writer.writeheader() for b in books: writer.writerow(asdict(b)) def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description=__doc__.splitlines()[1]) ap.add_argument("output", nargs="?", default="books.csv", help="output CSV path (default: books.csv)") ap.add_argument("--max-pages", type=int, default=None, help="stop after N catalogue pages (default: all)") ap.add_argument("--detail", action="store_true", help="also fetch each product page to fill in the " "category field (slower: 1 request per book)") ap.add_argument("--workers", type=int, default=4, help="concurrent product-page fetches for --detail " "(default: 4)") ap.add_argument("--verbose", "-v", action="store_true", help="log progress to stderr") args = ap.parse_args(argv) print("Scraping books.toscrape.com ...", file=sys.stderr) try: books = scrape_all(max_pages=args.max_pages, verbose=args.verbose) except RuntimeError as err: print(f"ERROR: {err}", file=sys.stderr) return 1 if not books: print("ERROR: no books parsed — site layout may have changed.", file=sys.stderr) return 2 if args.detail: print(f"Enriching {len(books)} product pages " f"({args.workers} workers) ...", file=sys.stderr) filled = enrich_with_details(books, workers=args.workers, verbose=args.verbose) print(f"Filled category on {filled} books.", file=sys.stderr) out = Path(args.output) write_csv(books, out) cats = {b.category for b in books if b.category} print(f"Done: {len(books)} books, {len(cats)} categories -> {out}", file=sys.stderr) return 0 if __name__ == "__main__": raise SystemExit(main())