File size: 11,906 Bytes
61bb557
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
"""
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 <a> 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 <li> 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())