#!/usr/bin/env python3 """Collect a paginated listing into a CSV file, politely. Out of the box this collects all 1,000 books on https://books.toscrape.com/, a practice shop Zyte publishes for people learning to scrape: 50 pages of 20 books, no JavaScript, and no robots.txt rule against any page. python3 scrape_to_csv.py # every page into books.csv python3 scrape_to_csv.py --max-pages 2 # a quick look first python3 scrape_to_csv.py --excel # a CSV that Excel opens with the £ intact python3 -m unittest test_scrape_to_csv # the tests, offline Needs Python 3.9 or newer and nothing else: no pip install. To point it at another site you are allowed to collect, change START_URL, FIELDS, parse_page() and check_row(), and keep the rest. Read that site's terms first: this script obeys robots.txt, but it cannot read terms for you. Guide and updates: https://scrapingapiprices.com/guides/python-scraping-to-csv Copyright 2026 Scraping API Prices. Free to use, change and share under the MIT License. """ # SPDX-License-Identifier: MIT from __future__ import annotations import argparse import csv import email.utils import os import random import re import sys import time import urllib.error import urllib.parse import urllib.request import urllib.robotparser from datetime import datetime, timezone from decimal import Decimal, InvalidOperation from html.parser import HTMLParser START_URL = "https://books.toscrape.com/" # Say who is asking. On a site that is not a practice site, put your own name and a way to reach you here. USER_AGENT = "scrape-to-csv-starter/1.0 (+https://scrapingapiprices.com/guides/python-scraping-to-csv)" DELAY_SECONDS = 1.0 # pause between pages; a longer Crawl-delay in robots.txt wins TIMEOUT_SECONDS = 30 MAX_ATTEMPTS = 4 # one request and up to three retries RETRY_STATUSES = {408, 425, 429, 500, 502, 503, 504} MAX_WAIT_SECONDS = 120 # a site that asks for a longer pause gets it: the run stops instead # The schema: one CSV column per field, in this order. check_row() refuses a row that does not fit, so a page # that changed shows up as an error, never as a quiet column of blanks. FIELDS = ["title", "price", "currency", "rating", "in_stock", "product_url", "listing_url", "scraped_at"] RATINGS = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5} CURRENCIES = {"£": "GBP", "$": "USD", "€": "EUR"} class FetchError(Exception): """A page could not be fetched, or answered with something other than the page.""" class Refused(Exception): """robots.txt does not allow this address for this user agent.""" class LayoutChanged(Exception): """A listing page gave no rows: the selectors no longer match what the site sends.""" class RowError(ValueError): """One parsed row does not fit the schema.""" def log(message: str) -> None: print(message, file=sys.stderr, flush=True) # --------------------------------------------------------------------------------------------------------------- # A small HTML tree with CSS-style lookups, built on the standard library's parser, so nothing needs installing. # select() understands what a listing page needs: "tag", ".class", "tag.class", "#id" and descendants ("li.next a"). VOID_TAGS = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"} class Node: def __init__(self, tag: str, attrs: dict[str, str]): self.tag = tag self.attrs = attrs self.children: list[Node | str] = [] @property def classes(self) -> list[str]: return self.attrs.get("class", "").split() def text(self) -> str: """The element's text with runs of whitespace collapsed, as a reader sees it.""" parts: list[str] = [] stack: list[Node | str] = [self] while stack: item = stack.pop() if isinstance(item, str): parts.append(item) else: stack.extend(reversed(item.children)) return " ".join("".join(parts).split()) class _TreeBuilder(HTMLParser): def __init__(self) -> None: super().__init__(convert_charrefs=True) self.root = Node("#document", {}) self.open = [self.root] def handle_starttag(self, tag, attrs): node = Node(tag, {name: value or "" for name, value in attrs}) self.open[-1].children.append(node) if tag not in VOID_TAGS: self.open.append(node) def handle_startendtag(self, tag, attrs): self.open[-1].children.append(Node(tag, {name: value or "" for name, value in attrs})) def handle_endtag(self, tag): # Close the nearest open element with this name; a stray end tag is ignored, as browsers do. for depth in range(len(self.open) - 1, 0, -1): if self.open[depth].tag == tag: del self.open[depth:] return def handle_data(self, data): if self.open[-1].tag not in ("script", "style"): self.open[-1].children.append(data) def parse_html(html: str) -> Node: builder = _TreeBuilder() builder.feed(html) builder.close() return builder.root def _matches(node: Node, step: str) -> bool: head, *classes = step.split(".") tag, _, element_id = head.partition("#") if tag and node.tag != tag: return False if element_id and node.attrs.get("id") != element_id: return False return all(name in node.classes for name in classes) def _descendants(node: Node): stack = list(reversed([c for c in node.children if isinstance(c, Node)])) while stack: current = stack.pop() yield current stack.extend(reversed([c for c in current.children if isinstance(c, Node)])) def select(node: Node, selector: str) -> list[Node]: """Every element under node matching a selector such as "article.product_pod" or "li.next a".""" found = [node] for step in selector.split(): matched: list[Node] = [] seen: set[int] = set() for base in found: for element in _descendants(base): if id(element) not in seen and _matches(element, step): seen.add(id(element)) matched.append(element) found = matched return found def select_one(node: Node, selector: str) -> Node | None: found = select(node, selector) return found[0] if found else None # --------------------------------------------------------------------------------------------------------------- # The two parts to rewrite for another site: what one listing page holds, and what a valid row looks like. def parse_page(html: str, page_url: str) -> tuple[list[dict[str, str]], str | None]: """The rows on one listing page, as text, and the address of the next page (None on the last one).""" doc = parse_html(html) rows = [] for card in select(doc, "article.product_pod"): link = select_one(card, "h3 a") price = select_one(card, "p.price_color") stars = select_one(card, "p.star-rating") stock = select_one(card, "p.availability") rows.append({ "title": (link.attrs.get("title") or link.text()) if link else "", "price": price.text() if price else "", "rating": next((c for c in stars.classes if c != "star-rating"), "") if stars else "", "in_stock": stock.text() if stock else "", "product_url": urllib.parse.urljoin(page_url, link.attrs.get("href", "")) if link else "", }) next_link = select_one(doc, "li.next a") href = next_link.attrs.get("href") if next_link else None return rows, (urllib.parse.urljoin(page_url, href) if href else None) def check_row(raw: dict[str, str]) -> dict[str, str]: """The row in the schema's types, or RowError naming the field that does not fit.""" title = raw.get("title", "").strip() if not title: raise RowError("title is empty") price_text = raw.get("price", "").strip() match = re.fullmatch(r"(\D*?)\s*(\d[\d,]*(?:\.\d+)?)", price_text) if not match: raise RowError(f"price {price_text!r} is not a number") symbol = match.group(1).strip() if symbol not in CURRENCIES: hint = " (the page was read in the wrong character set)" if "Â" in symbol else "" raise RowError(f"price {price_text!r} has no currency this schema knows{hint}") try: price = Decimal(match.group(2).replace(",", "")).quantize(Decimal("0.01")) except InvalidOperation as error: raise RowError(f"price {price_text!r} is not a number") from error rating = RATINGS.get(raw.get("rating", "")) if rating is None: raise RowError(f"rating {raw.get('rating', '')!r} is not One to Five") stock = raw.get("in_stock", "").lower() if "out of stock" in stock: in_stock = "no" elif "in stock" in stock: in_stock = "yes" else: raise RowError(f"stock {raw.get('in_stock', '')!r} says neither in nor out of stock") url = raw.get("product_url", "") if not url.startswith(("https://", "http://")): raise RowError(f"product_url {url!r} is not a web address") return {"title": title, "price": str(price), "currency": CURRENCIES[symbol], "rating": str(rating), "in_stock": in_stock, "product_url": url} # --------------------------------------------------------------------------------------------------------------- # Fetching: one request at a time, a pause between pages, retries only for answers that mean "try again later". def api_address(url: str) -> str: """The request address: the page itself, or a scraping API's address when SCRAPER_API_URL is set. Pay for an API only when the site needs a feature this script lacks (pages built by JavaScript, a block on your address, pages from a chosen country). SCRAPER_API_URL is the API's request address with {url} where the page goes and {key} where your key goes; the key itself sits in SCRAPER_API_KEY, never in this file. An address without {key} sends the key as "Authorization: Bearer", for APIs that ask for it there. """ template = os.environ.get("SCRAPER_API_URL", "").strip() if not template: return url key = os.environ.get("SCRAPER_API_KEY", "") return template.replace("{url}", urllib.parse.quote(url, safe="")).replace("{key}", urllib.parse.quote(key, safe="")) def api_headers() -> dict[str, str]: template = os.environ.get("SCRAPER_API_URL", "").strip() key = os.environ.get("SCRAPER_API_KEY", "") return {"Authorization": f"Bearer {key}"} if template and key and "{key}" not in template else {} def request(address: str, user_agent: str, opener=urllib.request.urlopen, extra_headers: dict[str, str] | None = None): """One GET: (status, headers, body) for any HTTP answer. Raises OSError when no answer arrives.""" req = urllib.request.Request(address, headers={ "User-Agent": user_agent, "Accept": "text/html,application/xhtml+xml;q=0.9,*/*;q=0.8", **(extra_headers or {}), }) try: with opener(req, timeout=TIMEOUT_SECONDS) as response: return response.status, response.headers, response.read() except urllib.error.HTTPError as error: try: body = error.read() except OSError: body = b"" return error.code, error.headers, body def retry_after_seconds(headers) -> float | None: value = headers.get("Retry-After") if headers is not None else None if not value: return None value = value.strip() if value.isdigit(): return float(value) try: when = email.utils.parsedate_to_datetime(value) except (TypeError, ValueError): return None if when.tzinfo is None: when = when.replace(tzinfo=timezone.utc) return max(0.0, (when - datetime.now(timezone.utc)).total_seconds()) def get(url: str, user_agent: str, *, through_api: bool = True, opener=urllib.request.urlopen, sleep=time.sleep): """GET with polite retries: a timeout, 429 or 5xx waits and tries again. Other answers return as they are. Messages name the page, never the API address, so a key in SCRAPER_API_URL stays out of logs. """ address, extra = (api_address(url), api_headers()) if through_api else (url, {}) problem = "" for attempt in range(1, MAX_ATTEMPTS + 1): headers = None try: status, headers, body = request(address, user_agent, opener, extra) except OSError as error: problem = f"no answer ({type(error).__name__})" else: if status not in RETRY_STATUSES: return status, headers, body problem = f"HTTP {status}" if attempt == MAX_ATTEMPTS: break asked = retry_after_seconds(headers) if asked is not None and asked > MAX_WAIT_SECONDS: raise FetchError(f"{url}: {problem}, and the site asks for a {asked:.0f} s pause; run again later") wait = asked if asked is not None else min(MAX_WAIT_SECONDS, 2 ** attempt + random.uniform(0, 1)) log(f" {url}: {problem}; waiting {wait:.0f} s before attempt {attempt + 1} of {MAX_ATTEMPTS}") sleep(wait) raise FetchError(f"{url}: {problem} after {MAX_ATTEMPTS} attempts") def decode(body: bytes, headers) -> str: charset = headers.get_content_charset() if headers is not None else None if not charset: declared = re.search(rb"]+charset=[\"']?([\w-]+)", body[:4096], re.IGNORECASE) charset = declared.group(1).decode("ascii") if declared else "utf-8" try: return body.decode(charset, errors="replace") except LookupError: return body.decode("utf-8", errors="replace") def load_robots(start_url: str, user_agent: str, fetch=get) -> urllib.robotparser.RobotFileParser: """The site's robots.txt rules, read the way RFC 9309 says: none published means none apply.""" robots_url = urllib.parse.urljoin(start_url, "/robots.txt") rules = urllib.robotparser.RobotFileParser(robots_url) try: status, headers, body = fetch(robots_url, user_agent, through_api=False) except FetchError: status, headers, body = None, None, b"" if status == 200: rules.parse(decode(body, headers).splitlines()) elif status is not None and 400 <= status < 500: rules.allow_all = True # no robots.txt: nothing is disallowed else: rules.disallow_all = True # the site could not say: assume nothing is allowed, and stop return rules # --------------------------------------------------------------------------------------------------------------- def scrape(start_url: str = START_URL, out_path: str = "books.csv", *, max_pages: int = 0, delay: float = DELAY_SECONDS, user_agent: str = USER_AGENT, excel: bool = False, fetch=get, sleep=time.sleep) -> dict[str, int]: """Follow the listing from start_url, page by page, and write every valid row to out_path.""" rules = load_robots(start_url, user_agent, fetch) if not rules.can_fetch(user_agent, start_url): raise Refused(f"robots.txt does not allow {start_url} for this user agent; collect nothing here") pause = max(delay, float(rules.crawl_delay(user_agent) or 0)) host = urllib.parse.urlsplit(start_url).netloc part_path = out_path + ".part" # rows land here as they arrive; renamed to out_path when the run ends seen_pages: set[str] = set() seen_items: set[str] = set() pages = written = refused = 0 url: str | None = start_url with open(part_path, "w", newline="", encoding="utf-8-sig" if excel else "utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=FIELDS) writer.writeheader() while url: if url in seen_pages: log(f" {url} was already read; the pagination loops, so the run stops here") break if not rules.can_fetch(user_agent, url): log(f" robots.txt does not allow {url}; the run stops here") break if pages: sleep(pause) status, headers, body = fetch(url, user_agent) if status != 200: why = " (often a block: check the site's terms before going further)" if status in (401, 403) else "" raise FetchError(f"{url} answered HTTP {status}{why}") scraped_at = datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z") raw_rows, next_url = parse_page(decode(body, headers), url) if not raw_rows: raise LayoutChanged( f"{url} gave no rows: the selectors in parse_page() match nothing there. Save the page and " "look: a changed layout, a block page, or content that only JavaScript fills in.") for raw in raw_rows: try: row = check_row(raw) except RowError as error: refused += 1 log(f" refused a row on {url}: {error}") continue if row["product_url"] in seen_items: continue seen_items.add(row["product_url"]) writer.writerow({**row, "listing_url": url, "scraped_at": scraped_at}) written += 1 handle.flush() pages += 1 seen_pages.add(url) log(f"page {pages}: {len(raw_rows)} rows read, {written} written so far") if max_pages and pages >= max_pages: break if next_url and urllib.parse.urlsplit(next_url).netloc != host: log(f" the next page {next_url} is on another site; the run stops here") next_url = None url = next_url os.replace(part_path, out_path) return {"pages": pages, "rows": written, "refused": refused} def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Collect a paginated listing into a CSV file, politely.") parser.add_argument("--start-url", default=START_URL, help="the first listing page (default: %(default)s)") parser.add_argument("--out", default="books.csv", help="the CSV file to write (default: %(default)s)") parser.add_argument("--max-pages", type=int, default=0, help="stop after this many pages (default: every page)") parser.add_argument("--delay", type=float, default=DELAY_SECONDS, help="seconds between pages (default: 1)") parser.add_argument("--user-agent", default=USER_AGENT, help="who is asking, sent with every request") parser.add_argument("--excel", action="store_true", help="mark the file as UTF-8 so Excel shows £ and accents") args = parser.parse_args(argv) if args.user_agent == USER_AGENT and urllib.parse.urlsplit(args.start_url).netloc != urllib.parse.urlsplit(START_URL).netloc: log("Tip: set --user-agent to something that names you, so the site's owner can reach you.") started = time.monotonic() try: result = scrape(args.start_url, args.out, max_pages=args.max_pages, delay=args.delay, user_agent=args.user_agent, excel=args.excel) except (FetchError, Refused, LayoutChanged) as error: log(f"Stopped: {error}") return 1 log(f"Wrote {result['rows']} rows from {result['pages']} pages to {args.out} " f"in {time.monotonic() - started:.0f} s.") if result["refused"]: log(f"{result['refused']} rows did not fit the schema and were left out; the messages above say why.") return 1 return 0 if __name__ == "__main__": sys.exit(main())