# Scrapling Book Deals: agent kit

Give this whole file to your coding agent (Claude Code, Codex, any agent with a terminal) and say:
"Follow this kit and build the Book Deals project."

What you get at the end: a Scrapling spider that reads every book in a practice store (books.toscrape.com:
50 listing pages + 1,000 book pages), survives being stopped halfway without losing a book, and a `deals.html`
dashboard (books, categories, average price, five-star books under £20, the cheapest book in every category).
Built and run for our Scrapling YouTube tutorial (2026-11-20), Scrapling 0.5.1; every command here was run in a clean test folder.

---

## Instructions for the agent

You are setting up and running a small web scraping project for the user. Work step by step, run every command
yourself, and check each "Expected" line before moving on. If a step fails, use the Troubleshooting table at the end
before trying anything else. Tell the user what you did and show them the final numbers.

### Safety rules (follow all of them)
1. Only scrape `books.toscrape.com` and `quotes.toscrape.com`. They are practice sites run by Zyte and built to be
   scraped ("We love being scraped!"). Do NOT point this project at any other site unless the user asks, and if they
   do, first read that site's terms of service and its robots.txt with them.
2. Install only inside a new virtual environment in the project folder. Never use `sudo`, never `pip install` into the
   system Python, never change the user's shell profile.
3. Pin the version: `scrapling[all]==0.5.1`. Do not upgrade it during this kit.
4. Do not read, print or copy any `.env` file, key or password. This project needs no account and no key.
5. Do not use proxies, CAPTCHA solvers or any "bypass" option. None are needed here.

---

## Phase 1: Check Python (needs 3.10 or newer)

```bash
python3 --version
```
Expected: `Python 3.10` or newer. Scrapling 0.5.1 declares 3.10 to 3.13; our build ran on 3.14.8 without problems.
A Mac's built-in `/usr/bin/python3` is 3.9: if that is what you see, ask the user to install Python 3.13
(python.org or `brew install python@3.13`) and use that `python3.13` below instead.

## Phase 2: Project folder, virtual environment, install

```bash
mkdir -p book-deals && cd book-deals
python3 -m venv .venv
source .venv/bin/activate
pip install "scrapling[all]==0.5.1"
scrapling --version
scrapling install
python -m patchright install chromium
```
Expected: `Scrapling, version 0.5.1`. `scrapling install` downloads Playwright's Chromium (a few hundred MB).
The last line downloads the Chromium build that Scrapling's browser fetcher (Patchright) needs; without it,
`StealthyFetcher` crashes with "Executable doesn't exist" (see Troubleshooting). Total disk: about 1.5 GB.

## Phase 3: First scrape (one page)

```bash
scrapling extract get "https://books.toscrape.com/" books.md -s "article.product_pod"
head -8 books.md
```
Expected: `Fetched (200)` and a Markdown file that starts with "A Light in the Attic" and "£51.77".

Create `first.py`:
```python
from scrapling.fetchers import Fetcher

page = Fetcher.get("https://books.toscrape.com/")
for book in page.css("article.product_pod")[:5]:
    print(book.css("p.price_color::text").get(), book.css("h3 a::attr(title)").get())
```
```bash
python first.py
```
Expected first line: `£51.77 A Light in the Attic`.

## Phase 4: The spider (the whole store)

Create `books_spider.py` exactly like this:
```python
import json
from scrapling.spiders import Spider

RATING = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}

class BookSpider(Spider):
    name = "books"
    start_urls = ["https://books.toscrape.com/catalogue/page-1.html"]
    concurrent_requests = 8
    robots_txt_obey = True

    async def parse(self, response):
        for book in response.css("article.product_pod"):
            yield response.follow(book.css("h3 a::attr(href)").get(), callback=self.parse_book)
        next_page = response.css("li.next a::attr(href)").get()
        if next_page:
            yield response.follow(next_page)

    async def parse_book(self, response):
        stock = response.css("p.availability").first.get_all_text(strip=True)
        yield {
            "title": response.css("h1::text").get(),
            "price": float(response.css("p.price_color::text").get().lstrip("£")),
            "rating": RATING[response.css("p.star-rating::attr(class)").get().split()[-1]],
            "in_stock": int(stock.split("(")[1].split()[0]),
            "category": response.css("ul.breadcrumb li:nth-child(3) a::text").get(),
            "url": response.url,
        }

    async def on_scraped_item(self, item):
        with open("books.jsonl", "a") as f:
            f.write(json.dumps(item) + "\n")
        return item

result = BookSpider(crawldir="crawl-state").start()
result.items.to_csv("books.csv")
print(f"{len(result.items)} books in {result.stats.elapsed_seconds:.0f} seconds")
```
Run it (start from a clean slate so old rows don't mix in):
```bash
rm -rf crawl-state books.jsonl books.csv
python books_spider.py
wc -l books.jsonl
```
Expected: the log scrolls (one line per page), then `1000 books in ...` (about 18 seconds in our test) and
`1000 books.jsonl`.

Why `books.jsonl` and not just `books.csv`: the spider can be paused with Ctrl+C and resumed by running the same
command again (that is what `crawldir` does), but the checkpoint stores the to-do list, not the books, and `to_csv`
rewrites the file with only that run's books. The `on_scraped_item` hook appends every book as it arrives, so
`books.jsonl` always has everything. (Optional test: start it, Ctrl+C after a few seconds, run it again, then
`wc -l books.jsonl` should still say 1000.)

## Phase 5: The dashboard

Create `report.py`:
```python
import json, html
from collections import defaultdict

books = [json.loads(line) for line in open("books.jsonl")]
books = list({b["url"]: b for b in books}.values())  # one row per book

deals = sorted((b for b in books if b["rating"] == 5 and b["price"] < 20), key=lambda b: b["price"])
cheapest = {}
for b in sorted(books, key=lambda b: b["price"]):
    cheapest.setdefault(b["category"], b)
per_category = defaultdict(int)
for b in books:
    per_category[b["category"]] += 1
biggest = sorted(per_category.items(), key=lambda kv: -kv[1])[:10]

def row(b):
    return (f'<tr><td><a href="{b["url"]}">{html.escape(b["title"])}</a></td><td>{html.escape(b["category"])}</td>'
            f'<td>{"★" * b["rating"]}</td><td>{b["in_stock"]}</td><td class="p">£{b["price"]:.2f}</td></tr>')

top = biggest[0][1]
bars = "".join(f'<div class="bar"><span>{html.escape(c)}</span><i style="width:{n / top * 100:.0f}%"></i><b>{n}</b></div>' for c, n in biggest)
page = f"""<!doctype html><meta charset="utf-8"><title>Book Deals</title>
<style>
body{{font:16px system-ui;margin:0;background:#f6f3ee;color:#1d1b18}} main{{max-width:1100px;margin:auto;padding:40px}}
h1{{font:700 44px Georgia;margin:0}} .sub{{color:#6b645a;margin:6px 0 28px}}
.kpis{{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}} .kpi{{background:#fff;border-radius:14px;padding:18px 20px;box-shadow:0 2px 10px #0001}}
.kpi b{{display:block;font:700 34px Georgia}} .kpi span{{color:#6b645a}}
h2{{font:700 24px Georgia;margin:36px 0 12px}} table{{width:100%;border-collapse:collapse;background:#fff;border-radius:14px;overflow:hidden}}
td{{padding:9px 14px;border-top:1px solid #eee}} .h td{{font-weight:700;color:#6b645a !important;border-top:0}} a{{color:#1d1b18}} .p{{font-weight:700;color:#0a7a4b}} td:nth-child(3){{color:#e2a400}}
.chart{{background:#fff;border-radius:14px;padding:16px 20px}} .bar{{display:flex;align-items:center;gap:12px;margin:5px 0}}
.bar span{{flex:0 0 170px;color:#6b645a}} .bar i{{height:18px;background:#e8590c;border-radius:0 6px 6px 0}} .bar b{{font-weight:700}}
.chips{{display:flex;flex-wrap:wrap;gap:8px}} .chip{{background:#fff;border-radius:99px;padding:6px 12px;box-shadow:0 1px 4px #0001}}
</style><main>
<h1>Book Deals</h1><div class="sub">{len(books):,} books scraped from books.toscrape.com (a practice store) with Scrapling</div>
<div class="kpis"><div class="kpi"><b>{len(books):,}</b><span>books</span></div><div class="kpi"><b>{len(cheapest)}</b><span>categories</span></div>
<div class="kpi"><b>£{sum(b["price"] for b in books) / len(books):.2f}</b><span>average price</span></div>
<div class="kpi"><b>{len(deals)}</b><span>5-star books under £20</span></div></div>
<h2>Biggest categories</h2><div class="chart">{bars}</div>
<h2>5-star books under £20</h2><table><tr class="h"><td>Title</td><td>Category</td><td>Rating</td><td>In stock</td><td>Price</td></tr>{"".join(row(b) for b in deals)}</table>
<h2>Cheapest book in every category</h2><div class="chips">{"".join(f'<span class="chip">{html.escape(c)} · £{b["price"]:.2f}</span>' for c, b in sorted(cheapest.items()))}</div>
</main>"""
open("deals.html", "w").write(page)
print(f"{len(books)} books, {len(deals)} five-star deals under £20 -> deals.html")
```
```bash
python report.py
```
Expected: `1000 books, 42 five-star deals under £20 -> deals.html`. Tell the user to open `deals.html` in their
browser (on a Mac: `open deals.html`). It shows 1,000 books, 50 categories, an average price of £35.07.
("Default" and "Add a comment" are real category names on this practice store, not a bug.)

## Phase 6 (optional): a JavaScript page

```python
# js_page.py
from scrapling.fetchers import Fetcher, StealthyFetcher

url = "https://quotes.toscrape.com/js/"
print("Fetcher:", len(Fetcher.get(url).css("div.quote")), "quotes")

page = StealthyFetcher.fetch(url, headless=True)
quotes = page.css("div.quote")
print("StealthyFetcher:", len(quotes), "quotes")
print(quotes[0].css("span.text::text").get())
```
Expected: `Fetcher: 0 quotes` (the quotes are drawn by JavaScript after the page loads) and `StealthyFetcher: 10 quotes`.

## Phase 7 (optional): the redesign test (adaptive selectors)

This is the test from the video: save the store's first page, make a "redesigned" copy where the price moves from
`<p class="price_color">` into `<span class="amount">`, and watch the normal selector find 0 while adaptive finds it.

```bash
mkdir -p ../redesign/site && cd ../redesign
```
Create `make_redesign.py`:
```python
# make_redesign.py: save the store's first page, then make a "redesigned" copy of it
import re
from scrapling.fetchers import Fetcher

before = Fetcher.get("https://books.toscrape.com/catalogue/page-1.html").html_content
after = before.replace('<article class="product_pod">', '<div class="book-card"><div class="card-body">')
after = after.replace("</article>", "</div></div>").replace('class="product_price"', 'class="buy-box"')
after = re.sub(r'<p class="price_color">([^<]*)</p>', r'<span class="amount">\1</span>', after)
open("shop-before.html", "w").write(before)
open("shop-after.html", "w").write(after)
print("price tags before:", before.count("price_color"), "after:", after.count('class="amount"'))
```
Create `adaptive.py`:
```python
import sys
from scrapling.fetchers import Fetcher

Fetcher.configure(adaptive=True)
page = Fetcher.get("http://localhost:8765/")

if sys.argv[1] == "save":
    prices = page.css("p.price_color", auto_save=True)
    print("Saved:", len(prices), "prices, first one", prices[0].text)
else:
    print("Normal selector:", len(page.css("p.price_color")), "prices")
    found = page.css("p.price_color", adaptive=True)
    print("Adaptive found:", found[0].text, "now inside a", found[0].tag)
    prices = [found[0], *found[0].find_similar()]
    print("Plus its look-alikes:", len(prices), "prices")
```
```bash
python make_redesign.py
cp shop-before.html site/index.html
python -m http.server 8765 -d site > /dev/null 2>&1 &
python adaptive.py save
cp shop-after.html site/index.html
python adaptive.py check
kill %1
```
Expected: `Saved: 20 prices, first one £51.77`, then after the redesign `Normal selector: 0 prices`,
`Adaptive found: £51.77 now inside a span`, `Plus its look-alikes: 20 prices`.
Adaptive saves a fingerprint of the FIRST match only, kicks in only when the selector finds nothing, keeps its
database inside the virtual environment by default, and can guess wrong (open issue #574): check the first run after
a site changes.

---

## Troubleshooting (all of these happened in our build)

| What you see | Why | Fix |
|---|---|---|
| `0 books`, `"error": 1000`, `AttributeError: 'Selectors' object has no attribute 'get_all_text'` | `.css()` returns a list of matches; `get_all_text` works on one element | use `.first.get_all_text(strip=True)` (already in the code above) |
| After Ctrl+C and a resume, `books.csv` has fewer than 1,000 rows | the checkpoint saves the to-do list, not the books; `to_csv` rewrites the file each run | read `books.jsonl` (the `on_scraped_item` hook appends every book) |
| `Executable doesn't exist at .../ms-playwright/chromium-1248/...` + "Looks like Playwright was just installed" | `scrapling install` fetched Playwright's Chromium (build 1255); the browser fetcher runs on Patchright, which wants build 1248 (open pull request #585 on the repo) | `python -m patchright install chromium` |
| `ImportError: cannot import name 'DynamicFetcher'` | removed in Scrapling 0.5; older tutorials and AI answers still use it | use `StealthyFetcher` |
| `ModuleNotFoundError` when importing fetchers or spiders | installed `scrapling` without the extras | `pip install "scrapling[all]==0.5.1"` |
| Titles end in "..." | the link text is shortened on the listing page | use `h3 a::attr(title)` or the book page's `h1::text` |

## Sources
- Scrapling: https://github.com/D4Vinci/Scrapling (BSD-3-Clause), docs https://scrapling.readthedocs.io/en/latest/
- Release 0.5.1 (2026-11-04): https://github.com/D4Vinci/Scrapling/releases/tag/v0.5.1
- Browser build mismatch: https://github.com/D4Vinci/Scrapling/pull/585
- Practice sites (Zyte): https://books.toscrape.com/ and https://quotes.toscrape.com/
- Only the Spider reads robots.txt, and only with `robots_txt_obey = True`. Before scraping any real site, read its
  terms of service and robots.txt.
