Web scraping with Python to CSV: a starter that runs
One Python file collects every item on a listing, page after page, into a CSV file. It reads robots.txt first, pauses between pages, retries only when a site says to try again later, and leaves out any row that does not fit its columns. It needs Python 3.9 or newer and nothing else, and running it costs nothing. Out of the box it collects all 1,000 books from a practice shop made to be scraped; then you point it at a site you are allowed to collect.
Run it
Save the file in an empty folder, open a terminal there, and read two pages first, then the whole shop:
python3 scrape_to_csv.py --max-pages 2
python3 scrape_to_csv.py The second command reads all 50 pages into books.csv; at the starter's one-second pause our run took 75 seconds. On Windows, type py where these say python3. If the file is going to Excel, add --excel: the CSV then starts with a marker that tells Excel it is UTF-8, so the £ signs and accented letters arrive intact. The tests need no network: python3 -m unittest test_scrape_to_csv.
Read the whole starter (450 lines)
#!/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"<meta[^>]+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())
What it writes
| title | price | currency | rating | in_stock | product_url | listing_url | scraped_at |
|---|---|---|---|---|---|---|---|
| A Light in the Attic | 51.77 | GBP | 3 | yes | https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html | https://books.toscrape.com/ | 2026-10-29T05:52:41Z |
| Tipping the Velvet | 53.74 | GBP | 1 | yes | https://books.toscrape.com/catalogue/tipping-the-velvet_999/index.html | https://books.toscrape.com/ | 2026-10-29T05:52:41Z |
| Soumission | 50.10 | GBP | 1 | yes | https://books.toscrape.com/catalogue/soumission_998/index.html | https://books.toscrape.com/ | 2026-10-29T05:52:41Z |
| Sharp Objects | 47.82 | GBP | 4 | yes | https://books.toscrape.com/catalogue/sharp-objects_997/index.html | https://books.toscrape.com/ | 2026-10-29T05:52:41Z |
| Sapiens: A Brief History of Humankind | 54.23 | GBP | 5 | yes | https://books.toscrape.com/catalogue/sapiens-a-brief-history-of-humankind_996/index.html | https://books.toscrape.com/ | 2026-10-29T05:52:41Z |
One row per book, with the same 8 columns in the same order every time: the title; the price as a plain number and its currency in a column of its own, so a spreadsheet can add the prices up; the star rating as a number from 1 to 5; whether the book is in stock, as yes or no; the full addresses of the book's page and of the listing page it came from; and the time, in UTC, the page was read. That run read 50 pages and wrote 1,000 rows, one for every book in the shop. The shop's prices and ratings are made up, so the numbers mean nothing beyond the exercise.
The practice shop, and why it may be scraped
The starter's first target is books.toscrape.com, a fictional bookshop on toscrape.com, a web scraping sandbox under the logo of Zyte, a scraping company whose own tutorials scrape it. The sandbox's front page calls the shop "a fictional bookstore that desperately wants to be scraped" and "a safe place for beginners learning web scraping", and every page of the shop says it is a demo for scraping practice, with prices and ratings assigned at random.
Its robots.txt answers "not found" (HTTP 404). Under the robots.txt standard, RFC 9309, a crawler may then access any page on the site, and the shop publishes no terms of use. It is also a fair test of the parts that break on real sites: 1,000 books on 50 pages of 20, a "next" link on every page but the last, and every book in the HTML the server sends, with no JavaScript needed.
What the starter does, step by step
- Reads robots.txt before anything else, the way RFC 9309 says: no file (a 4xx answer) means no rules; a file the server fails to deliver (a 5xx answer, or no answer) means stop. A Crawl-delay longer than the starter's own pause wins.
- Fetches one page at a time, one second apart, with a User-Agent that says what it is. Before you collect anything beyond the practice shop, change it to name you and a way to reach you.
- Retries only what means "try again later": a timeout, HTTP 429 or a 5xx answer, up to three more times with longer waits, and exactly as long as the site's Retry-After asks. If a site asks for more than two minutes, the run stops and tells you to come back later. A 403 or a 404 is never retried: asking again does not change the answer, and repeating a refused request is not polite.
- Reads each page with Python's own HTML parser and finds the items with CSS selectors such as
article.product_podandli.next a, the kind your browser's developer tools show you. - Checks every row against the columns: a missing title, a price that is not a number, a rating outside 1 to 5. A row that fails is left out and named in the output, and the run ends with an error so a scheduled job notices. A page with no rows at all stops the run, because it means the page changed, blocked you or needs JavaScript; an empty CSV is never reported as a success.
- Follows the "next" link to the last page, and stops if the pages loop back or the link leads to another site.
- Writes rows as it goes into
books.csv.partand renames itbooks.csvat the end, so a stopped run keeps what it collected and a file called books.csv is always complete.
Point it at a site of your own
Before you change a line, check that you may: read the site's terms of use and its robots.txt, look for an official API or a data download, which is usually steadier and often cheaper (when the official API beats scraping), and leave personal data alone unless you have a lawful reason to hold it. Then:
- Set
START_URLto the first page of the listing, andUSER_AGENTto your name or project and an address where the site's owner can reach you. - Open the listing in your browser, right-click an item and choose Inspect. Note the element that repeats once per item and the link to the next page, and put those selectors into
parse_page(), the one function that knows the shop's layout:
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) - Change
FIELDSto the columns you want, andcheck_row()to what a valid value looks like on that site. - Paste a trimmed copy of one listing page into
SAMPLEin the tests, change the expected values, and run them. - Run two pages with
--max-pages 2, open the CSV, then run the rest. Keep the one-second pause, or make it longer on a small site.
If the run stops with "gave no rows", open the page's source (Ctrl+U, not Inspect). If the items are missing from the source, the page builds them with JavaScript. Look in the developer tools' Network tab for the request that brings them in, often JSON you can read directly with the same fetch code; otherwise render the page with a browser on your own machine (Playwright is free), or let an API render it for you, as priced below.
What your job takes
An example is filled in: type over it with your own listing. Nothing you type leaves the page.
10,000 items at 20 a page, opening each item's own page, weekly: 10,500 pages a run, 42,000 a month.
The starter fetches them for $0 in API fees, in at least 2 hours 55 minutes a run at one page a second.
No paid API is needed for this job. If you would rather not run it yourself, 42,000 plain pages a month cost from $14.99 a month on FlyByAPIs AI Web Scraper (Pro), the lowest complete bill among 44 web scraping APIs; price read Nov 28, 2026.
- FlyByAPIs AI Web Scraper$14.99Pro · checked Nov 28, 2026
- ScrapeOps$15.0050,000 credits · checked Nov 28, 2026
- BrowserCloud$19.00Hobby · checked Nov 28, 2026
- ScrapingAnt$19.00Enthusiast · checked Nov 28, 2026
- ScrapingBee$19.00Hobby · checked Nov 8, 2026
See all 44 web scraping APIs for these pages, with failure rates and yearly billing.
Pages are the listing pages (items divided by items a page, rounded up), plus one page per item if you open each, times the runs a month. The time counts the starter's one-second pause and nothing else; a slow site adds its own response time to every page. The bills come from the same dated pricing records and the same arithmetic as this site's market table, for every web scraping API that publishes a price, before retries.
When an API is worth paying for
The starter runs on your own computer for nothing. Pay an API only for a feature it lacks:
- Pages built by JavaScript. An API renders them in its own browser, usually at several times the price of a plain page (what JavaScript rendering costs).
- A site that blocks plain requests. An API's protected-site mode sends them from other addresses, at a higher rate. Use it only where the site's terms allow collecting.
- Pages as seen from one country. Some APIs include a country choice and some charge extra (which APIs target a country).
The starter can send its requests through an API with no change to the code. Set SCRAPER_API_URL to the API's request address, with {url} where the page address goes and {key} where your key goes, and SCRAPER_API_KEY to your key. The starter still reads robots.txt from the site itself, and your key never appears in its messages. These addresses ask each API to render JavaScript, as its own documentation showed on Oct 29, 2026:
- ScraperAPI pricing
https://api.scraperapi.com/?api_key={key}&render=true&url={url}Its documentation asks for its own parameters before url. Its documentation - ZenRows pricing
https://api.zenrows.com/v1/?apikey={key}&js_render=true&url={url}Rendering is off unless js_render is true. Its documentation - ScrapingBee pricing
https://app.scrapingbee.com/api/v1?url={url}Rendering is on by default. With no {key} in the address, the starter sends your key in an Authorization header, where ScrapingBee now asks for it. Its documentation
export SCRAPER_API_URL='https://api.zenrows.com/v1/?apikey={key}&js_render=true&url={url}'
export SCRAPER_API_KEY='your key'
python3 scrape_to_csv.py In Windows PowerShell, write $env:SCRAPER_API_URL = '…' and $env:SCRAPER_API_KEY = 'your key' instead of the two export lines. Every API counts pages or credits differently; the credit converter turns a plan's credits into pages for each of them.
Sources
- toscrape.com/
- books.toscrape.com/
- www.rfc-editor.org/rfc/rfc9309.html
- docs.scraperapi.com/javascript-rendering/overview
- docs.scraperapi.com/synchronous-apis/using-the-api-endpoint
- docs.zenrows.com/fetch/api-reference
- www.scrapingbee.com/documentation/
Read on Oct 29, 2026. The starter's code, columns and sample rows above are read from the same files you download, and the site's tests run them against two saved pages of the shop and the CSV of our run.