Concept Explanation
You now have the tools to fetch a million pages. That capability comes with an obligation, and not just a moral one — careless scrapers get IP-banned, get their API keys revoked, and occasionally get their employer a letter from a lawyer.
The uncomfortable truth is that a badly written scraper is indistinguishable from a denial-of-service attack. A for loop with no delay can issue hundreds of requests per second. Small sites run on modest servers; you can take one down by accident while collecting data you were welcome to have.
This lesson is the professional layer on top of the technical one.
robots.txt: The Site's Stated Wishes
Nearly every site publishes https://example.com/robots.txt, a plain-text file describing which paths automated clients should avoid.
User-agent: *
Disallow: /admin/
Disallow: /api/internal/
Crawl-delay: 10
User-agent: BadBot
Disallow: /
It is not a security mechanism and it cannot stop you. It is the site telling you, in a machine-readable way, what it considers acceptable. Ignoring it is a deliberate choice you should be able to defend.
Python reads it for you:
from urllib.robotparser import RobotFileParser
rp = RobotFileParser()
rp.set_url("https://example.com/robots.txt")
rp.read()
if rp.can_fetch("MyBot/1.0", "https://example.com/products"):
print("Allowed")
The Hierarchy of Politeness
Work down this list and stop at the first option that exists:
| Preference | Why |
|---|---|
| 1. An official API | Structured, stable, rate-limited on purpose, explicitly permitted |
| 2. A bulk data export or dataset | No load on their servers at all |
| 3. An RSS/Atom or sitemap feed | Designed for machines |
| 4. Scraping HTML | Fragile, unwelcome, and your last resort |
If a site offers an API and you scrape the HTML anyway, you have chosen the harder, rougher, more breakable path for no reason.
Rate Limiting: The One Non-Negotiable
| Situation | Reasonable pace |
|---|---|
Crawl-delay given in robots.txt | Exactly that, or slower |
| Small independent site | 1 request every 2–5 seconds |
| Large site, no stated limit | 1 request per second |
| Documented API | Whatever the docs allow, minus a margin |
Terms of Service and the Law
This is genuinely jurisdiction-dependent and this lesson is not legal advice, but three factors come up in nearly every discussion:
- Public vs authenticated: scraping pages behind a login you agreed to terms for is a much weaker position than scraping public pages.
- Personal data: names, emails, and profiles are regulated (GDPR, CCPA). "It was publicly visible" is not a defence for storing it.
- Copyright: facts are generally not copyrightable; the expression of them usually is. Republishing scraped articles wholesale is a different act from computing statistics over them.
When the data is personal, commercial, or bulk, ask someone qualified before you ship.
Code Example #1 (Basic)
A crawler that reads the rules before it starts.
import time
import requests
from urllib.robotparser import RobotFileParser
from urllib.parse import urljoin, urlparse
USER_AGENT = "ResearchBot/1.0 (+https://example.com/bot-info)"
def build_checker(site_root):
rp = RobotFileParser()
rp.set_url(urljoin(site_root, "/robots.txt"))
try:
rp.read()
except Exception:
return None, 5.0 # unreadable robots.txt -> assume nothing, go slow
delay = rp.crawl_delay(USER_AGENT) or 2.0
return rp, float(delay)
def polite_crawl(urls):
root = "{0}://{1}".format(*urlparse(urls[0])[:2])
rules, delay = build_checker(root)
for url in urls:
if rules and not rules.can_fetch(USER_AGENT, url):
print(f"SKIP (disallowed): {url}")
continue
r = requests.get(url, headers={"User-Agent": USER_AGENT}, timeout=10)
print(f"{r.status_code} {url}")
time.sleep(delay) # the line beginners delete and regret
polite_crawl([
"https://httpbin.org/html",
"https://httpbin.org/status/200",
])
Code Example #2 (Intermediate)
A reusable throttle plus a cache, so re-running your script costs the site nothing.
import hashlib
import time
from pathlib import Path
import requests
CACHE = Path(".scrape_cache")
CACHE.mkdir(exist_ok=True)
class Throttle:
"""Guarantees at least `min_gap` seconds between calls."""
def __init__(self, min_gap=2.0):
self.min_gap = min_gap
self.last = 0.0
def wait(self):
elapsed = time.monotonic() - self.last
if elapsed < self.min_gap:
time.sleep(self.min_gap - elapsed)
self.last = time.monotonic()
throttle = Throttle(min_gap=2.0)
session = requests.Session()
session.headers["User-Agent"] = "ResearchBot/1.0 (+https://example.com/bot-info)"
def get_cached(url):
"""Fetch a URL once; every later call reads from disk."""
key = hashlib.sha256(url.encode()).hexdigest()[:16]
path = CACHE / f"{key}.html"
if path.exists():
print(f" (cache) {url}")
return path.read_text(encoding="utf-8")
throttle.wait()
r = session.get(url, timeout=10)
r.raise_for_status()
path.write_text(r.text, encoding="utf-8")
print(f" (fetched) {url}")
return r.text
# The parsing logic can now be rewritten twenty times
# without sending a single extra request.
for _ in range(3):
get_cached("https://httpbin.org/html")
The cache is the single highest-value habit in scraping. Most of your iterations are on the parsing code, not the fetching — and every re-run against a live server is load you did not need to create.
Common Mistakes
- No delay between requests: the default behaviour of a bare
forloop is effectively an attack. Add a sleep before you add anything else. - Re-fetching while debugging: hitting the live site fifty times to test one regex. Cache the HTML to disk and iterate offline.
- Lying about who you are: spoofing Chrome's user agent to evade a block is a decision with consequences. Identify your bot and include a contact URL.
- Ignoring 429 and 503: those statuses mean "you are hurting us." Backing off is not optional.
- Scraping personal data "because it's public": visibility is not permission. Regulated data stays regulated.
- Running unattended with no cap: a bug in a link-following loop can queue a million URLs overnight. Always bound total requests and depth.
- Skipping the API: checking for
/apior a developer portal takes two minutes and often saves the whole project.
Best Practices
- Look for an API first, every time: then a dataset, then a feed, then HTML.
- Read
robots.txtprogrammatically:RobotFileParseris in the standard library — there is no excuse. - Identify yourself with a contact URL: an admin who can reach you sends an email; one who cannot sends a firewall rule.
- Cache aggressively during development: fetch once, parse a hundred times.
- Throttle by default, not as an afterthought: build the delay into your fetch helper so it cannot be forgotten.
- Scrape only the fields you need: less data collected is less data to secure, justify, and delete.
- Prefer off-peak hours: overnight in the site's own timezone costs them the least.
- Stop when asked: if you get a takedown request, comply first and negotiate afterwards.
Practice Exercises
- The Rule Reader: Fetch
robots.txtfrom three sites you use and print, for each, the disallowed paths and anyCrawl-delay. Note which of them would forbid the scraper you were planning. - The Throttled Fetcher: Wrap the
Throttleclass above into apolite_get(url)helper that enforces a minimum gap, retries once on 429 honouringRetry-After, and refuses any URLrobots.txtdisallows. - The Cache Layer: Add disk caching to a scraper you have already written, then measure how long a second full run takes with and without it. Write down the number of requests you avoided sending.