Web Scraping with Python: Requests, Parsing and When to Stop
Web scraping with Python takes two libraries: requests to download a page and BeautifulSoup to pull values out of its HTML with CSS selectors. Add a robots.txt check, a delay between requests and a CSV writer, and you have a working scraper in about 80 lines. This tutorial builds one for books.toscrape.com, a site made for scraping practice, then covers the point where a scraper costs more to maintain than an API call.
What do you need for web scraping in Python?
You need Python 3, the requests library for HTTP and BeautifulSoup for parsing, and nothing else for a static site. Python's standard library covers the rest: urllib.robotparser for robots rules, csv for output and time for pacing. You don't need a browser, a proxy service or a framework to start. Install the two packages with pip:
pip install requests beautifulsoup4
We used Python 3 with requests 2.34.2 and beautifulsoup4 4.15.0. BeautifulSoup's built-in html.parser is enough here; lxml is faster on large pages if you install it.
The target is books.toscrape.com, a sandbox bookshop built for people learning to scrape. Each book on a listing page sits in an <article class="product_pod"> with the title in an h3 link, the price in p.price_color, a p.star-rating whose second class is the rating word, and an availability line. Practising on a sandbox keeps you clear of a real shop's terms while you learn.
How do you build the scraper, step by step?
The scraper below fetches listing pages one at a time, checks each URL against robots.txt, parses every book into a dictionary, waits between pages and saves the result to CSV. It's the whole program, about 80 lines, and the five steps after it explain each part and the choices behind it.
import csv
import time
from functools import lru_cache
from urllib.parse import urljoin
from urllib.robotparser import RobotFileParser
import requests
from bs4 import BeautifulSoup
BASE = "https://books.toscrape.com/"
USER_AGENT = "books-tutorial/1.0 (you@example.com)"
DELAY_SECONDS = 2
RATINGS = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}
session = requests.Session()
session.headers["User-Agent"] = USER_AGENT
@lru_cache(maxsize=1)
def robots():
parser = RobotFileParser(urljoin(BASE, "/robots.txt"))
parser.read()
return parser
def allowed(url):
return robots().can_fetch(USER_AGENT, url)
def fetch(url):
resp = session.get(url, timeout=30)
if resp.status_code == 404:
return None
resp.raise_for_status()
resp.encoding = "utf-8"
return resp.text
def parse_books(html, page_url):
soup = BeautifulSoup(html, "html.parser")
books = []
for card in soup.select("article.product_pod"):
link = card.select_one("h3 a")
price = card.select_one("p.price_color")
rating = card.select_one("p.star-rating")
stock = card.select_one("p.availability")
if not (link and price):
continue # skip a card whose layout changed, rather than crash
rating_word = next((c for c in rating["class"] if c in RATINGS), None) if rating else None
books.append({
"title": link.get("title") or link.get_text(strip=True),
"price": float(price.get_text(strip=True).lstrip("£")),
"rating": RATINGS.get(rating_word),
"in_stock": bool(stock and "In stock" in stock.get_text()),
"url": urljoin(page_url, link["href"]),
})
return books
def scrape(max_pages=3):
rows = []
for n in range(1, max_pages + 1):
url = urljoin(BASE, f"catalogue/page-{n}.html")
if not allowed(url):
print(f"robots.txt disallows {url}; stopping")
break
html = fetch(url)
if html is None:
break # past the last page
books = parse_books(html, url)
if not books:
break
rows.extend(books)
print(f"page {n}: {len(books)} books")
time.sleep(DELAY_SECONDS)
return rows
if __name__ == "__main__":
rows = scrape()
with open("books.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["title", "price", "rating", "in_stock", "url"])
writer.writeheader()
writer.writerows(rows)
print(f"saved {len(rows)} books to books.csv")
books.toscrape.com wasn't reachable from the environment we wrote this in, so we couldn't run the script against the live site. We tested parse_books() on an HTML snippet with the site's markup (two book cards and one broken card) and the pagination loop with a mocked session. On the snippet, the first card parsed to:
{'title': 'A Light in the Attic', 'price': 51.77, 'rating': 3, 'in_stock': True,
'url': 'https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html'}
and the broken card was skipped. Run the script yourself and compare a few rows with the pages before you build on it.
Step 1: check robots.txt before you fetch
robots() downloads the site's robots.txt once and allowed() asks it whether your user agent may fetch a URL. The rules are the site's published instructions for automated clients (RFC 9309, 2022). The RFC is explicit that they aren't access authorization, so also read the site's terms of use; a scraper that obeys robots.txt can still break a site's terms.
Step 2: fetch politely
The session sends one User-Agent that names your scraper and a contact address, so the site's operators can tell who you are. timeout=30 stops a hung connection from freezing the job. A 404 returns None, which the loop treats as the end of the catalogue; any other error status raises, because a 403 or 503 means you should stop and look, not push on.
Step 3: parse with CSS selectors
soup.select("article.product_pod") returns every book card; inside each, select_one() finds one element or returns None. The title attribute holds the full title where the link text is shortened. The rating lives in a class name, so the code picks the class that matches a rating word. Prices arrive as text like £51.77 and become floats.
Step 4: paginate with a delay
Listing pages follow the pattern catalogue/page-N.html. The loop walks them in order, stops at a 404 or an empty page, and sleeps DELAY_SECONDS between requests. Two seconds is a cautious default for a small site; if robots.txt gives a Crawl-delay, robots().crawl_delay(USER_AGENT) returns it, and you should use the longer of the two.
Step 5: save and check the output
csv.DictWriter writes one row per book. The printed count per page is your monitoring: if a page that used to give 20 rows gives 0, the layout changed. Scrapers fail quietly, so log those counts somewhere you'll see them. To load the rows into a database instead, Web Data to a Warehouse covers Postgres.
When should you stop scraping and use something else?
Stop when keeping the scraper working costs more than the data is worth to you. A scraper for one static site, run weekly, is cheap. The cost grows with every site, every layout change and every page that needs a browser. These are the signals:
- The page needs JavaScript. If
requestsreturns HTML without the data, the page builds it in the browser. You now need a headless browser such as Playwright, which is slower and heavier to run. - The site blocks you. A CAPTCHA, a 403 or a challenge page means the site doesn't want automated access. Don't try to get around it with rotating proxies or CAPTCHA solvers. Look for an official API or a licensed data source, or leave it.
- There's an official API. If the site offers an API with the data you need, use it: it's stable, documented and allowed.
- You maintain many parsers. Each site breaks on its own schedule. Ten sites means ten parsers to watch.
- You need search results or listings from large sites. These change layout often and limit automated access. A structured endpoint returns named fields instead.
Scraper or API: What Maintaining a Scraper Really Involves puts numbers on that maintenance.
What does the same job look like with an API call?
An API call replaces the fetching and the parsing. For a page with no structured endpoint, GET /v1/web-scraper/scrape takes a url (up to 2048 characters) and returns the page as json or markdown (response_type), with an optional javascript parameter for pages that render in the browser. For sites in the catalogue, a structured endpoint returns named fields. Both cost 1 credit per successful call.
import os
import requests
API = "https://api.perceptlayer.com"
HEADERS = {"X-API-Key": os.environ["API_KEY"]}
resp = requests.get(
f"{API}/v1/google-search/search",
params={"query": "best restaurants in Berlin", "hl": "en", "safe": "off"},
headers=HEADERS,
timeout=60,
)
resp.raise_for_status()
for result in resp.json()["organic_results"]:
print(result["position"], result["title"], result["link"])
print("credits used:", resp.headers.get("X-Credits-Used"))
We didn't run this against the live API. This is the recorded response to that request, trimmed:
{
"organic_results": [
{
"position": 1,
"title": "The Best Restaurants in Berlin - Food Guide & Map",
"link": "https://andershusa.com/best-restaurants-berlin-germany-guide/",
"displayed_link": "https://andershusa.com › best-restaurants-berlin-german...",
"source": "Anders & Kaitlin",
…
},
{
"position": 2,
"title": "Restaurants - Berlin",
"link": "https://guide.michelin.com/us/en/berlin-region/berlin/restaurants",
…
}
],
"related_searches": [
{
"query": "Best restaurants in Berlin for tourists",
…
}
],
…
}
There's no selector to maintain: the loop reads organic_results[].title and link. The Google Search API page lists its seven endpoints, and the Web Scraper API page has the scrape endpoint.
What does it cost compared with your own scraper?
Your own scraper costs no credits but costs your time and its hosting. An API call costs 1 credit, and a failed call costs nothing and returns X-Credits-Used: 0. A weekly job of 500 pages is 500 × 4 = 2,000 credits a month; every account gets 100 free credits once, after verifying an email address, enough for a 100-page test, and the Starter pack holds 10,000, or 5 months of that job. A daily job of 2,000 pages is 2,000 × 30 = 60,000 credits a month, within the Growth pack's 200,000. See pricing for what credits cost.
The API has limits too: 1 request a second on a free account and at least 5 a second on a paying one. If you exceed them you get a 429 with Retry-After; HTTP 429 Too Many Requests shows how to handle it.
To compare on your own target, run the scrape endpoint in the playground on the Web Scraper API page with a URL you'd otherwise parse, or get a free API key.
APIs in this post
Frequently asked questions
Is web scraping with Python legal?
It depends on the site, the data and where you are, not on the language. Public pages are generally lower risk than pages behind a login, and personal data brings privacy law into play. Read the site's terms, respect robots.txt, don't collect personal data without a lawful basis, and don't get around blocks. For anything commercial, ask a lawyer.
Which is better for scraping, BeautifulSoup or Scrapy?
BeautifulSoup is a parser; Scrapy is a crawling framework with scheduling, retries, throttling and pipelines built in. For one site and a few hundred pages, requests and BeautifulSoup are simpler. For many pages and sites, Scrapy saves you writing the plumbing yourself. Neither renders JavaScript on its own.
Why does my scraper return empty results?
Usually the data isn't in the HTML you downloaded: the page loads it with JavaScript after the first response. Print resp.text and search it for a value you can see in the browser. If it isn't there, look for the JSON request the page makes in your browser's network tab, use a headless browser, or call the scrape endpoint with javascript set.
How fast can I scrape a website?
As slowly as the job allows. Follow any Crawl-delay in robots.txt, keep to one request at a time on small sites, and back off at the first 429 or 503. A 2-second delay is a cautious default for a small site. Scraping faster than a site can serve hurts its other visitors and gets you blocked.
How much does scraping a page through the API cost?
One credit per successful call, for the scrape endpoint and for nearly every structured endpoint. Failed calls cost nothing. Every account gets 100 free credits once, after verifying an email address, and purchased credits last 12 months. The credits docs explain how balances work.