πΈοΈ Advanced Web Scraping
in Python
Advanced web scraping in Python: ethics, robots.txt, rate limiting, backoff, sessions, BeautifulSoup and lxml selectors, pagination, Playwright, caching and CSV/JSON output.
What this lesson is about
Basic scraping is easy to start: download a page, find some tags, print the text. Scraping that keeps working, treats the website fairly and produces clean data is a different job. Real projects such as price trackers, research datasets, job-board monitors and archive tools run for weeks, hit thousands of pages and meet rate limits, odd HTML, pagination and pages that only fill in after JavaScript runs.
This lesson is about doing that properly. I start with the question people skip, whether you should scrape a site at all, then move through reading robots.txt, pacing your requests with a rate limiter, retrying with backoff, sending honest headers, parsing with the standard library and with BeautifulSoup and lxml, following pagination, handling JavaScript pages with Playwright, caching so you never download the same page twice, and saving results as CSV and JSON.
Your browser cannot make network requests from these examples, so the runnable blocks work on embedded HTML strings, a fake clock and an in-memory fake fetcher. That is also how I recommend you develop a scraper: save a page once, then write and test the parsing code against the saved copy. Blocks that need the network or extra libraries are marked as static, and you can run them on your own computer. If you have not used HTTP in Python yet, read requests first, and for the output side see JSON/CSV.
What you will learn
- βJudge whether a scraping job is acceptable: terms, personal data, load and alternatives such as official APIs
- βCheck permissions with
urllib.robotparserand honour crawl delays - βBuild a token-bucket rate limiter and a retry schedule with exponential backoff and jitter
- βSend clear headers and reuse connections with a
requests.Session - βParse HTML with
html.parser, BeautifulSoup and CSS selectors - βWalk through paginated listings without looping forever
- βKnow when a page needs a real browser and how Playwright fits in
- βCache responses and write clean results to CSV and JSON
Why programmers should learn this
- β Many useful datasets, such as public notices, product listings and documentation, are only available as web pages, so scraping is often the only way to get them into a program.
- β A scraper that ignores pacing and permissions can overload a small site or get your address blocked; polite design protects both the site and your project.
- β Separating fetching, parsing and saving makes a scraper testable, so a small HTML change on the site means editing one function instead of rewriting everything.
- β Caching and retries turn a fragile script that dies at page 400 into a job you can stop, resume and trust.
- β The same skills, HTTP, HTML structure, selectors and data cleaning, carry over to testing web apps, building monitors and working with APIs.
Should you scrape this? Ethics, terms and the law
Before writing a line of code I ask four questions. Is there an official API or a downloadable dataset? If so, use it: it is more stable, faster and clearly allowed. Do the site's terms of use or robots.txt forbid automated access? Does the data include personal information about people? And how much load will my scraper put on the server?
I am not a lawyer and the rules differ between countries, so treat this as practical guidance, not legal advice. Terms of service can restrict automated access even to public pages, copyright may apply to the text and images you collect, and data protection laws can apply to personal data even when it is publicly visible. Logging in to a site or bypassing a technical block is a much riskier act than reading public pages at a gentle pace. If a project is commercial or involves people's data, ask a qualified person before you start.
On the technical side, good manners are simple. Identify yourself with a clear User-Agent and a way to contact you, fetch only what you need, run slowly, cache everything so you never repeat a request, and stop if the site asks you to. The rest of this lesson turns those principles into code, so politeness becomes part of the program instead of something you remember to do.
Scraper pre-flight checklist 1. Is there an official API, export or dataset? (use it first) 2. Have I read the terms of use for automated access? 3. Does robots.txt allow my paths and user agent? 4. Is any of the data personal? (avoid it unless I have a clear lawful reason) 5. Do I send a descriptive User-Agent with contact details? 6. Is my request rate low, with delays, retries and backoff? 7. Do I cache pages so each URL is downloaded once? 8. Can I stop immediately if the site owner asks?
Line by line
- 1The first question saves the most work: an API returns structured data without any HTML parsing.
- 2-3Terms and
robots.txtare different documents; check both. - 4Personal data raises legal and ethical duties that a hobby script rarely thinks about.
- 5-7These three habits are the technical core of polite scraping and are built in the next sections.
- 8Be ready to comply with a request to stop and to delete data you should not hold.
Public does not automatically mean free to collect and reuse. Check the terms, and treat personal data with extra care.
Reading robots.txt with urllib.robotparser
robots.txt is a plain text file at the root of a site that tells automated clients which paths they should avoid. It is a convention, not a security system: it will not stop a bad client, but good scrapers respect it, and ignoring it is the quickest way to look hostile. Python ships a parser for it in urllib.robotparser.
Normally you would call set_url() and read() to download the file, but the parser can also read rules you already have as a list of lines through parse(). That is perfect for learning and for tests, because nothing touches the network. After parsing, can_fetch(user_agent, url) answers yes or no, crawl_delay(user_agent) returns the requested pause in seconds if there is one, and site_maps() lists any sitemap URLs.
Rules are matched per user agent, with the * group as the fallback. The first matching rule in a group wins in Python's parser, so order matters: an Allow that should override a Disallow has to come first. In your real scraper, fetch robots.txt once per site, keep the parser object, and ask it before every URL.
from urllib.robotparser import RobotFileParser
rules = """User-agent: *
Allow: /private/help
Disallow: /private/
Disallow: /search
Crawl-delay: 2
User-agent: BadBot
Disallow: /
Sitemap: https://example.com/sitemap.xml
""".splitlines()
rp = RobotFileParser()
rp.parse(rules)
base = "https://example.com"
for path in ["/articles/1", "/private/data", "/private/help", "/search?q=x"]:
print(path, rp.can_fetch("MyScraper", base + path))
print("BadBot:", rp.can_fetch("BadBot", base + "/articles/1"))
print("delay:", rp.crawl_delay("MyScraper"))
print("sitemaps:", rp.site_maps())/articles/1 True /private/data False /private/help True /search?q=x False BadBot: False delay: 2 sitemaps: ['https://example.com/sitemap.xml']
Line by line
- 1
RobotFileParserlives in the standard library, so no install is needed. - 3-11A sample
robots.txtas a string split into lines. The*group applies to everyone; BadBot is banned completely. - 13-14Create the parser and feed it the lines instead of downloading anything.
- 16-18Check four paths.
/private/helpis allowed because itsAllowline comes before the broaderDisallow. - 20A specific user agent can have its own, stricter rules.
- 21-22Read the polite delay and sitemap addresses the site publishes.
In a live scraper you would write rp.set_url('https://example.com/robots.txt') and rp.read(), then call can_fetch before each request. Keep the answer for the whole run rather than downloading the file again each time.
Rate limiting: a token bucket you can test
A rate limiter decides how fast you may send requests. The simplest version is time.sleep(2) between pages, which is fine for small jobs. A token bucket is more flexible: the bucket holds up to capacity tokens, refills at a steady rate per second, and each request spends one token. If there are tokens you go straight away, so short bursts are allowed, but over time you cannot exceed the refill rate.
The trouble with testing anything that sleeps is that tests become slow and unreliable. The fix is to inject the clock. My limiter below takes a function that returns the current time and a function that waits, so in a test I pass a fake clock that I advance by hand. In production I pass time.monotonic and time.sleep. This is a useful pattern far beyond scraping.
Always use time.monotonic() for measuring intervals, not time.time(): the wall clock can jump when the system adjusts its time, and a jump backwards would break your maths. Also respect any Crawl-delay from robots.txt by choosing a rate no faster than one request per that many seconds.
class FakeClock:
def __init__(self):
self.now = 0.0
def time(self):
return self.now
def sleep(self, seconds):
self.now += seconds
class TokenBucket:
def __init__(self, rate, capacity, clock, sleep):
self.rate = rate # tokens added per second
self.capacity = capacity
self.tokens = capacity
self.clock = clock
self.sleep = sleep
self.last = clock()
def _refill(self):
now = self.clock()
self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
self.last = now
def acquire(self):
self._refill()
if self.tokens < 1:
wait = (1 - self.tokens) / self.rate
self.sleep(wait)
self._refill()
self.tokens -= 1
clock = FakeClock()
bucket = TokenBucket(rate=0.5, capacity=2, clock=clock.time, sleep=clock.sleep)
for i in range(6):
bucket.acquire()
print(f"request {i + 1} sent at t={clock.now:.1f}s")request 1 sent at t=0.0s request 2 sent at t=0.0s request 3 sent at t=2.0s request 4 sent at t=4.0s request 5 sent at t=6.0s request 6 sent at t=8.0s
Line by line
- 1-7A fake clock:
time()reports a number we control andsleep()just advances it, so nothing really waits. - 10-17The bucket stores its refill rate, capacity and the current token count, and remembers the last refill time.
- 19-22Refill adds tokens for the time that passed since last time, capped at capacity.
- 24-30
acquirerefills, waits just long enough for one full token if there is none, then spends a token. - 34-35Half a token per second means one request every two seconds, with a burst of two allowed at the start.
- 37-39Send six requests and print the simulated time of each one.
The first two requests go out at once because the bucket starts full, then the output settles into one request every two seconds. For a real scraper, build the bucket with time.monotonic and time.sleep.
Retries, exponential backoff and honest headers
Networks fail. A server might answer 429 (too many requests), 503 (temporarily unavailable) or just time out. Retrying immediately makes things worse, so use exponential backoff: wait 1 second, then 2, then 4, and so on up to a cap, and add jitter, a small random amount, so that many clients do not all retry at the same instant. If the server sends a Retry-After header, prefer that value.
Only retry errors that are likely to be temporary: timeouts, connection errors, 429 and 5xx responses. A 404 or 403 will not change by asking again, so give up on those. Always set a maximum number of attempts and a timeout on every request; a request without a timeout can hang a scraper forever.
Headers are part of being honest. Set a User-Agent that names your project and gives a contact address, and add Accept and Accept-Language if the site cares. Do not pretend to be a real browser to dodge blocks: if a site blocks you, that is a signal to slow down or ask for permission, not a puzzle to beat. A requests.Session reuses the TCP connection and keeps headers and cookies between calls, which is faster and kinder to the server.
import random
def backoff_delays(attempts, base=1.0, cap=30.0, seed=7):
rng = random.Random(seed)
delays = []
for n in range(attempts):
ceiling = min(cap, base * 2 ** n)
delays.append(round(rng.uniform(ceiling / 2, ceiling), 2))
return delays
print(backoff_delays(6))
print(backoff_delays(6, base=2.0, cap=10.0))
RETRYABLE = {429, 500, 502, 503, 504}
for code in [200, 404, 429, 503]:
print(code, "retry" if code in RETRYABLE else "do not retry")[0.66, 1.15, 3.3, 4.29, 12.29, 20.49] [1.32, 2.3, 6.6, 5.36, 7.68, 6.83] 200 do not retry 404 do not retry 429 retry 503 retry
Line by line
- 1
randomgives us jitter; we use a seeded generator so the output is repeatable. - 3-9For attempt
nthe ceiling doubles (1, 2, 4...) up tocap; the actual wait is a random value between half the ceiling and the ceiling. - 11-12Show a default schedule and one with a bigger base and a lower cap.
- 14-16Only temporary failures are worth retrying; a 404 stays a 404.
import time
import requests
session = requests.Session()
session.headers.update({
"User-Agent": "MyLearningScraper/1.0 (contact: you@example.com)",
"Accept-Language": "en",
})
def fetch(url, attempts=4):
for n in range(attempts):
try:
response = session.get(url, timeout=10)
except (requests.ConnectionError, requests.Timeout):
response = None
if response is not None and response.status_code == 200:
return response.text
if response is not None and response.status_code not in {429, 500, 502, 503, 504}:
raise RuntimeError(f"{url} gave {response.status_code}")
retry_after = response.headers.get("Retry-After") if response is not None else None
time.sleep(float(retry_after) if retry_after and retry_after.isdigit() else 2 ** n)
raise RuntimeError(f"gave up on {url}")Line by line
- 1-2
requestsis a third-party package, which is why this block is not run in the browser. - 4-8One session for the whole run, with a descriptive
User-Agentthat includes a contact address. - 10-13Each attempt uses a timeout, and a network error becomes
Noneso it can be retried. - 14-15Success returns the page text.
- 16-17A non-temporary status such as 404 raises immediately instead of retrying.
- 18-19Wait for the server's
Retry-Afterif it sent a number of seconds, otherwise back off exponentially.
Parsing HTML with the standard library
HTML is a tree of tags, and parsing means walking that tree and pulling out what you need. Python's built-in html.parser.HTMLParser is a streaming parser: you subclass it and it calls your methods, handle_starttag, handle_data and handle_endtag, as it reads the document. It is not as convenient as BeautifulSoup, but it needs no installation, runs everywhere including in your browser here, and teaches you what is happening under the hood.
The pattern is to keep a little state. When you see an <a> start tag you remember its href; while inside it, handle_data collects text; when the end tag arrives you store the finished pair. I also store the class attribute to tell product cards from navigation links. Real pages are messy, with missing quotes and unclosed tags, and HTMLParser copes with that without raising errors.
Remember to read attribute values defensively. attrs arrives as a list of (name, value) tuples, and value can be None for attributes with no value, so convert it to a dictionary and use .get(). Text often has stray whitespace and newlines, so strip it before storing.
from html.parser import HTMLParser
PAGE = """
<html><body>
<nav><a href="/home">Home</a></nav>
<div class="item"><a href="/book/1">Learning Python</a> <span class="price">19.50</span></div>
<div class="item"><a href="/book/2">Data Tricks</a> <span class="price">24.00</span></div>
<div class="item"><a href="/book/3">Web Basics</a> <span class="price">12.25</span></div>
</body></html>
"""
class ItemParser(HTMLParser):
def __init__(self):
super().__init__()
self.items = []
self._current = None
self._field = None
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == "div" and attrs.get("class") == "item":
self._current = {"title": "", "url": "", "price": ""}
elif self._current is not None and tag == "a":
self._current["url"] = attrs.get("href", "")
self._field = "title"
elif self._current is not None and tag == "span" and attrs.get("class") == "price":
self._field = "price"
def handle_data(self, data):
if self._current is not None and self._field:
self._current[self._field] += data.strip()
def handle_endtag(self, tag):
if tag in ("a", "span"):
self._field = None
elif tag == "div" and self._current is not None:
self.items.append(self._current)
self._current = None
parser = ItemParser()
parser.feed(PAGE)
for item in parser.items:
print(item)
print(sum(float(i["price"]) for i in parser.items)){'title': 'Learning Python', 'url': '/book/1', 'price': '19.50'}
{'title': 'Data Tricks', 'url': '/book/2', 'price': '24.00'}
{'title': 'Web Basics', 'url': '/book/3', 'price': '12.25'}
55.75Line by line
- 3-10An embedded HTML page: one navigation link we want to ignore and three product cards.
- 12-17Subclass
HTMLParser; keep the finished items, the item being built and the field we are currently reading. - 19-27On a start tag, begin a new item for
div.item, then note the link target and which field the next text belongs to. - 29-31Text between tags is appended to the current field, stripped of whitespace.
- 33-38On an end tag, stop reading the field, and when the card closes save it to the list.
- 40-44
feedruns the parser; print each item and add up the prices as numbers.
BeautifulSoup, lxml and CSS selectors
For most projects I reach for BeautifulSoup (pip install beautifulsoup4). It builds the whole tree in memory so you can search it with ease: soup.select('div.item') takes a CSS selector, select_one returns the first match or None, .get_text(strip=True) extracts clean text and element['href'] or element.get('href') reads an attribute. If you know CSS from web design, you already know most of the query language.
BeautifulSoup is a layer over a parser. You choose the parser as the second argument: 'html.parser' is built in, and 'lxml' (pip install lxml) is a fast C-based parser that handles broken markup well. lxml can also be used directly with XPath expressions such as //div[@class='item']/a/@href, which is powerful when selectors cannot express what you need, for example 'the table cell after the cell that says Price'.
Write selectors that survive redesigns. Prefer meaningful classes, data- attributes or the document structure over long chains such as div > div > div:nth-child(3). Handle missing elements on purpose, because select_one(...) returning None followed by .text is the most common scraper crash. And keep parsing in a function that takes an HTML string and returns plain dictionaries; then you can test it with a saved page and no network.
from bs4 import BeautifulSoup
html = """
<div class="item"><a href="/book/1">Learning Python</a> <span class="price">19.50</span></div>
<div class="item"><a href="/book/2">Data Tricks</a></div>
"""
soup = BeautifulSoup(html, "html.parser") # or "lxml" if installed
rows = []
for card in soup.select("div.item"):
link = card.select_one("a")
price = card.select_one("span.price")
rows.append({
"title": link.get_text(strip=True),
"url": link["href"],
"price": float(price.get_text(strip=True)) if price else None,
})
print(rows)[{'title': 'Learning Python', 'url': '/book/1', 'price': 19.5}, {'title': 'Data Tricks', 'url': '/book/2', 'price': None}]Line by line
- 1Import the BeautifulSoup class from the
bs4package. - 3-6Two cards; the second one has no price, as happens on real pages.
- 8Parse the string; the second argument picks the parser.
- 11-13
selectfinds everydiv.item; inside each cardselect_onefinds the first link and price element. - 14-18Build a dictionary per card;
get_text(strip=True)returns clean text and the price becomesNonewhen absent. - 20Print the list to see the clean rows.
Notice the conditional if price else None. Handling the absent case in the parser keeps one odd page from stopping a long run. Pair this with logging so that you can see which pages were missing fields.
Pagination and building a crawl loop
Most listings span several pages. There are three common patterns: page numbers in the URL (?page=2), a 'next' link in the HTML, and cursor-based pages where each response contains a token for the next one. A 'next' link is the most robust to follow because the site tells you where to go; with numbered pages you must decide when to stop, usually when a page returns no items.
Whatever the pattern, protect yourself against endless loops. Keep a set of URLs you have already visited, set a hard maximum number of pages, and stop when a page has no new items. Resolve relative links with urllib.parse.urljoin(base, href) so /page/3 becomes a full address.
The cleanest structure is a generator that yields items one page at a time. The consumer decides what to do with them, such as writing rows as they arrive, and your memory use stays small even for a huge crawl. Below, a dictionary stands in for the website so you can see the whole loop run with no network, and the fetch function is the one piece you would replace with a real request.
from urllib.parse import urljoin
from html.parser import HTMLParser
SITE = {
"https://shop.example/list?page=1": '<li>apple</li><li>pear</li><a class="next" href="/list?page=2">next</a>',
"https://shop.example/list?page=2": '<li>plum</li><a class="next" href="/list?page=3">next</a>',
"https://shop.example/list?page=3": '<li>fig</li><li>kiwi</li>',
}
def fetch(url):
return SITE[url] # a real scraper would make a request here
class ListParser(HTMLParser):
def __init__(self):
super().__init__()
self.items, self.next_href, self._in_li = [], None, False
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == "li":
self._in_li = True
elif tag == "a" and attrs.get("class") == "next":
self.next_href = attrs.get("href")
def handle_endtag(self, tag):
if tag == "li":
self._in_li = False
def handle_data(self, data):
if self._in_li:
self.items.append(data.strip())
def crawl(start_url, max_pages=10):
url, seen = start_url, set()
while url and url not in seen and len(seen) < max_pages:
seen.add(url)
parser = ListParser()
parser.feed(fetch(url))
yield from parser.items
url = urljoin(url, parser.next_href) if parser.next_href else None
print(list(crawl("https://shop.example/list?page=1")))
print(list(crawl("https://shop.example/list?page=1", max_pages=2)))['apple', 'pear', 'plum', 'fig', 'kiwi'] ['apple', 'pear', 'plum']
Line by line
- 1-2
urljointurns relative links into absolute ones. - 4-8A dictionary acts as a fake website with three pages, each linking to the next.
- 10-11The only function that would touch the network; swapping it is the whole change needed for a live run.
- 13-26A small parser that collects list items and remembers the
hrefof the 'next' link. - 28-35The crawl is a generator: follow the next link until there is none, stop on a repeated URL or when
max_pagesis reached. - 37-38The first call walks all three pages; the second is cut off by the page limit.
JavaScript pages and Playwright
Some pages deliver almost empty HTML and then build the content in the browser with JavaScript. If requests returns a skeleton while your browser shows a full page, you have two options. First, open the browser's network tab: the page often loads its data from a JSON endpoint, and calling that endpoint directly (if the terms allow it) is far easier and faster than rendering anything. Second, drive a real browser.
Playwright (pip install playwright, then playwright install to download browsers) controls Chromium, Firefox or WebKit from Python. You open a page, wait for the element you care about, and read the rendered HTML or query elements directly. It is slower and heavier than plain requests, because it runs a whole browser, so use it only for pages that truly need it, reuse one browser for many pages, and keep the same politeness rules, including rate limits and caching.
Waiting correctly is the big skill. Never use a fixed sleep; wait for a selector or a network condition instead, so the script is fast when the page is fast and patient when it is slow. Once you have the rendered HTML string from page.content(), hand it to the same BeautifulSoup parsing function you already wrote. That separation, fetch with a browser and parse with a function, keeps your code simple.
from playwright.sync_api import sync_playwright
from parsing import parse_items # your own BeautifulSoup function
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page(user_agent="MyLearningScraper/1.0 (contact: you@example.com)")
page.goto("https://example.com/js-listing", timeout=30000)
page.wait_for_selector("div.item")
html = page.content()
browser.close()
print(parse_items(html))Line by line
- 1Playwright's synchronous API keeps the code simple for scripts.
- 2The parsing function lives in your own module, so it can be tested without a browser.
- 4-5Start a Chromium browser inside a context manager so it is cleaned up.
- 6Open a page, setting the same honest user agent as the rest of the scraper.
- 7Navigate with a timeout so a hung site cannot block you forever.
- 8Wait until the element we need appears instead of sleeping for a guessed time.
- 9-10Take the rendered HTML and close the browser.
- 12Reuse the ordinary parser on the string.
Caching and saving clean CSV and JSON
A cache stores every response the first time you fetch it, so a re-run costs nothing and puts no load on the server. The simplest cache is a dictionary keyed by URL; the durable version writes each page to a file named after a hash of the URL, or uses sqlite3. While you are developing the parser you will run it hundreds of times, so a cache is the difference between a friendly scraper and a nuisance. Add an expiry time if the data changes.
When the data is extracted, save it in a format other tools can use. CSV suits flat tables and opens in a spreadsheet; JSON keeps nested structure and types. Python's csv.DictWriter writes a list of dictionaries with a header row, and json.dumps(..., indent=2, ensure_ascii=False) keeps non-English text readable. Use newline='' when opening real CSV files so you do not get blank lines on Windows. For the details of both formats, see JSON/CSV.
Clean as you go: convert prices to numbers, strip whitespace, use None for missing values and keep the source URL and the date fetched with each row. Those two extra columns make the dataset auditable later. The example writes to io.StringIO so you can see the file content without touching the disk; swap it for open('items.csv', 'w', newline='', encoding='utf-8') to save for real.
import csv, io, json
calls = []
cache = {}
def fetch(url):
if url in cache:
return cache[url]
calls.append(url) # records only real downloads
cache[url] = f"<page for {url}>"
return cache[url]
for url in ["/a", "/b", "/a", "/a", "/b"]:
fetch(url)
print("real downloads:", calls)
rows = [
{"title": "Learning Python", "price": 19.5, "source": "/book/1"},
{"title": "Data Tricks, 2nd ed.", "price": None, "source": "/book/2"},
]
buffer = io.StringIO()
writer = csv.DictWriter(buffer, fieldnames=["title", "price", "source"])
writer.writeheader()
writer.writerows(rows)
print(buffer.getvalue())
print(json.dumps(rows, indent=2, ensure_ascii=False))real downloads: ['/a', '/b']
title,price,source
Learning Python,19.5,/book/1
"Data Tricks, 2nd ed.",,/book/2
[
{
"title": "Learning Python",
"price": 19.5,
"source": "/book/1"
},
{
"title": "Data Tricks, 2nd ed.",
"price": null,
"source": "/book/2"
}
]Line by line
- 3-4A list that counts real downloads and a dictionary that serves as the cache.
- 6-11If the URL is cached return it; otherwise record a download and store the page.
- 13-15Five requests but only two distinct URLs, so only two downloads happen.
- 17-20Two cleaned rows; the missing price is
Noneand the title contains a comma. - 22-26
DictWriterwrites the header and the rows into an in-memory buffer; the csv module quotes the comma-containing title for us. - 28
indent=2makes the JSON readable andensure_ascii=Falsekeeps accents and other scripts intact.
A good rhythm is: fetch and cache, parse into dictionaries, clean and validate, then write. Each stage can be tested and re-run alone.
Common mistakes
β Ignoring robots.txt and terms of use
It is tempting to skip the checks because the script works without them. But a scraper that ignores the site's stated rules can get blocked, can break the terms of service and can create legal trouble. Check permissions first with RobotFileParser and read the terms.
β Hammering the server with no delay
A loop that fires requests as fast as it can looks like an attack. Use a rate limiter, honour Crawl-delay, and add backoff on 429 and 5xx responses so you slow down when the server is struggling.
β Retrying everything forever
Endless retries with no timeout or attempt limit can hang a program or keep hammering a site that has blocked you. Set timeouts, a maximum attempt count and retry only temporary errors.
β Writing brittle selectors and not handling missing elements
Selectors such as div > div > div:nth-child(3) break on any redesign, and calling .text on None crashes the run. Prefer meaningful classes, check for None, and log pages with missing fields.
β Re-downloading pages during development
Fetching the same URL on every test run wastes the site's resources and your time. Cache responses or save sample HTML, then develop the parser against the saved copy.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. Which standard-library module reads robots.txt rules?
urllib.robotparser.RobotFileParser parses the rules and answers can_fetch questions.Q2. Why use time.monotonic() instead of time.time() for a rate limiter?
Q3. What does jitter add to exponential backoff?
Q4. Which status code is usually worth retrying?
Q5. A page shows data in your browser but requests returns almost empty HTML. What should you check first?
Q6. What is the safest way to follow pagination?
Frequently asked questions
Is web scraping legal?
+It depends on the country, the site's terms, what data you take and how you use it. Public pages are not automatically free to reuse. Read the terms, respect robots.txt, avoid personal data and ask a qualified person for advice on commercial projects. This lesson is practical guidance, not legal advice.
Should I use BeautifulSoup or lxml?
+BeautifulSoup is friendlier and enough for most jobs. You can use lxml as its parser for speed and better handling of broken HTML, or use lxml directly when you want XPath. Start with BeautifulSoup and switch only if you need to.
When do I need Playwright or Selenium?
+Only when the content appears after JavaScript runs and there is no data endpoint you may call. A real browser is slower and heavier, so try plain requests and the network tab first.
How fast can I scrape?
+There is no universal number. Follow Crawl-delay if given, start slow, such as one request every few seconds, watch for 429 responses and slow down further when the server pushes back. Smaller sites need more care.
How do I stop my scraper breaking when the site changes?
+You cannot stop it entirely, but you can limit the damage: keep parsing in small testable functions, save sample pages as test fixtures, validate each row, log missing fields and alert yourself when the number of results suddenly drops.
Key takeaways
- βDecide first whether you should scrape: prefer an official API, read the terms and avoid personal data.
- βCheck
robots.txtwithurllib.robotparserand honour crawl delays. - βLimit your request rate with a testable token bucket, and retry only temporary errors with exponential backoff, jitter and timeouts.
- βParse with
html.parseror BeautifulSoup and keep selectors meaningful and defensive against missing elements. - βPaginate with a visited set and a page limit, use Playwright only when a page really needs a browser, and cache every response.
- βClean data as you extract it and save it to CSV or JSON with the source URL and fetch date.