Project
Stage 3 Project: Async Web Scraper (CLI)
Goal: Build a command-line tool that crawls a product website using
asyncio, parses the HTML with the standard library, stores the results in SQLite, and ships as a proper installable package. Time: ~8–10 hours · Uses: Parts 13–16 (plus everything from Stages 1–2). Standard library + pytest only.
Project brief
"SwadeshiBazaar" is a made-up shop that sells Indian handicrafts: sandalwood soap, Darjeeling tea, a Kashmiri shawl, Channapatna toys, a Madhubani painting. You don't work there — you want a little tool that visits every product page, reads the title and price off each one, and keeps a running catalogue in a database you can query without opening a browser.
That is what a web scraper is: a program that downloads pages and pulls structured data (title, price, links) out of their HTML.
This project never touches the real internet. A tiny local website — testserver/ — serves the sample pages on your own computer. The scraper crawls that. The approach (an async crawler, html.parser, SQLite, a CLI) is exactly what you would point at a real site; only the target is local, so the project works offline, every time, with no rate limits and no risk of scraping something you shouldn't.
A short demo on the sample pages (the full walkthrough is in tests_manual.md):
$ python main.py --db demo.db crawl http://127.0.0.1:8010/ --max-pages 20
Crawled 6 page(s), saved 6, in 0.64s.
$ python main.py --db demo.db list
Price Title URL
----------------------------------------------------------------------
₹85 Mysore Sandal Soap http://127.0.0.1:8010/product-1.html
₹450 Darjeeling First Flush Tea http://127.0.0.1:8010/product-2.html
₹599 Channapatna Wooden Toy Set http://127.0.0.1:8010/product-4.html
₹1,250 Madhubani Painting (Canvas) http://127.0.0.1:8010/product-5.html
₹3,200 Kashmiri Pashmina Shawl http://127.0.0.1:8010/product-3.html
----------------------------------------------------------------------
5 pages
$ python main.py --db demo.db stats
Crawl stats
===========
Pages stored: 6
With a price: 5
Average price: ₹1,117
Price range: ₹85 - ₹3,200
💡 Your
crawltiming will differ a little (0.64sis this machine, on this run) — that number depends on your computer, not on the code. Everything else is exact.
Files
| File / folder | What it is |
|---|---|
README.md |
This brief |
pyproject.toml |
Package metadata and the scraper CLI entry point (Part 16) |
main.py |
Thin entry point: python main.py ... without installing |
src/scraper/ |
The package: models, errors, fetcher, parser, storage, crawler, cli |
testserver/ |
A local HTTP server + 6 sample pages, so the scraper has something to crawl |
tests/ |
pytest tests: fetcher, parser, storage, and an end-to-end crawl (through the CLI, too) |
tests_manual.md |
CLI commands to try by hand, with the exact expected output |
Which Parts each piece uses
| Piece | Skills | Part |
|---|---|---|
fetcher.fetch_sync |
urllib.request, catching URLError |
Part 12 |
fetcher.fetch |
async def, await, asyncio.to_thread, Semaphore |
Part 13 |
crawler.crawl |
asyncio.gather, waves of concurrent downloads, a visited set |
Part 13 |
logger.info(...), --verbose |
logging, same pattern as the library project |
Part 11 |
time.perf_counter() in crawl |
timing your own code, not guessing | Part 14 |
Page, CrawlStats |
@dataclass, @dataclass(frozen=True) |
Part 9 |
StatsDict |
TypedDict: a fixed-shape dict with no behaviour |
Part 15 |
cli.run() |
match/case dispatch on the command name |
Part 15 |
ScraperError, FetchError |
custom exceptions, one base class | Part 6 |
parser.py |
html.parser.HTMLParser, tag callbacks |
stdlib (no third-party HTML library) |
storage.py |
SQLite, ? placeholders, ON CONFLICT ... DO UPDATE |
Part 12 |
pyproject.toml, [project.scripts], pip install -e . |
packaging, src layout, a CLI entry point | Part 16 |
argparse, subcommands, exit codes |
from the Stage 1 and Stage 2 projects | Stage 2 project |
Architecture
Each layer only talks to the one below it — the same split as the Stage 2 library project.
you type a command
│
▼
┌────────────────────────────┐
│ main.py (CLI) │ thin sys.path shim, calls scraper.cli.main()
└────────────┬───────────────┘
▼
┌────────────────────────────┐
│ scraper/cli.py │ argparse, match/case dispatch, "Error: ..." + exit codes
└────────────┬───────────────┘
│ calls crawl(seed_url, ...)
▼
┌────────────────────────────┐
│ scraper/crawler.py │ the crawl: waves of concurrent fetch+parse,
│ │ a visited set, asyncio.Semaphore(workers)
└───────┬──────────────┬─────┘
│ fetch(url) │ parse_page(url, html)
▼ ▼
┌───────────────┐ ┌───────────────┐
│ fetcher.py │ │ parser.py │ urllib + asyncio.to_thread html.parser
└───────────────┘ └───────────────┘
│
▼
┌────────────────────────────┐
│ scraper/storage.py │ Storage class: all the SQL, with ? placeholders
└────────────┬───────────────┘
▼
scraper_data.db (SQLite file)
models.py (Page, CrawlStats, StatsDict) and errors.py (ScraperError, FetchError)
are used by every layer.
testserver/server.py + testserver/pages/*.html
a local website the crawler crawls instead of the real internet.
Why split it like this? crawler.py never touches SQL and storage.py never touches HTML — you could point the same crawl() function at a different parser, or swap SQLite for another store, and only one file would change.
How to run
Open two terminals in this folder (Python 3.13+). On macOS/Linux type python3 instead of python.
Terminal 1 — start the local website (the scraper's target):
python testserver/server.py --serve --port 8010
# Serving .../testserver/pages at http://127.0.0.1:8010/ (Ctrl+C to stop)
Leave this running. Open http://127.0.0.1:8010/ in a browser if you want to see the pages it serves.
Terminal 2 — run the scraper:
python main.py --db demo.db crawl http://127.0.0.1:8010/ --max-pages 20
python main.py --db demo.db list
python main.py --db demo.db list --all # include the listing page too
python main.py --db demo.db stats
By default your data is saved in scraper_data.db next to main.py; --db demo.db here keeps a separate file for trying things out, the same convention as the library project.
Global options go before the command:
| Option | What it does |
|---|---|
--db PATH |
Use another SQLite file, e.g. --db demo.db for testing |
--verbose |
Show the log messages (one INFO line per page saved, Part 11) |
Running python main.py with no command prints the help text and exits 0 — it's a quick way to see every subcommand without opening this README.
Install it properly (Part 16)
pip install -e .
scraper --db demo.db crawl http://127.0.0.1:8010/ --max-pages 20
pip install -e . reads pyproject.toml, puts src/scraper on Python's import path, and creates a scraper command (the [project.scripts] entry point) that runs scraper.cli:main. From here on scraper ... and python main.py ... do exactly the same thing.
Features
| Command | What it does | Example |
|---|---|---|
crawl SEED_URL |
Crawl starting from one page, following links it finds | crawl http://127.0.0.1:8010/ --max-pages 20 |
list [--all] |
Show stored products (or every page, with --all) |
list --all |
stats |
Totals: pages stored, how many have a price, average/min/max price | stats |
crawl options: --max-pages N (stop after N pages, default 20) and --workers N (pages fetched at the same time, default 4).
Error handling: a problem you can fix prints one clear Error: ... line and exits with code 1. A page that cannot be fetched is logged as a WARNING and skipped — the crawl keeps going and still reports what it found. Wrong command-line usage (an unknown option) is caught by argparse: exit code 2.
How the crawl works
- Start with one URL in the frontier (the list of pages still to visit): the seed URL.
- Take the next batch of up to
workersURLs off the frontier and fetch them at the same time withasyncio.gather— this is the payoff of Part 13: the test server answers slowly on purpose, so fetching 4 pages at once is roughly 4× faster than one at a time. - Parse each page's HTML with
html.parser: pull out its<h1>title, anyclass="price"text (turned into a number —₹3,200→3200), and every link. - Save the page to SQLite. New links that point at the same site and haven't been seen before join the frontier.
- Repeat until the frontier is empty or
max_pagesis reached.
The sample pages are deliberately not all linked from the home page — index.html links to 3 products, and 2 more are only reachable by following a "You may also like" link from those. A crawler that only read the home page would miss them; this one doesn't, because it keeps following new links until there are none left (or the limit is hit).
Stretch goals
- 🟢
list --sort title: letlistsort by title instead of price. - 🟢 A
--format csvoption onlistthat writes the rows to a file instead of printing a table (Part 8). - 🟡 Respect
robots.txt-style rules: add apages/disallowed.htmlthat the crawler is told never to fetch, and test that it doesn't. - 🟡 Retry a failed fetch once (with a short
asyncio.sleep) before giving up on a page. - 🔴 Add a
--depth Noption so the crawl can be limited by link distance from the seed, not just by page count. - 🔴 Profile a crawl with
cProfile(Part 14) and report where the time actually goes — fetching, parsing, or SQLite.
Checklist
- I can write an async function that downloads several URLs at once, bounded by a
Semaphore. - I can parse HTML with
html.parser.HTMLParserwithout a third-party library. - I can store and query typed data in SQLite with
?placeholders. - I can tell a
TypedDictapart from adataclassand say when to use which. - I can use
match/caseto dispatch on a command name. - I can write pytest tests that start and stop a local server as a fixture.
- I can package a project with
pyproject.tomland run it as an installed CLI command. -
python -m pytest -q testspasses and every command intests_manual.mdgives the expected output.
Next
🎉 Stage 3 done! Go back to the roadmap and get ready for Stage 4: Data structures and algorithms.