The one-line mental model
Prefer a documented API over scraping HTML; when you must scrape, treat the target server politely â respect robots.txt, throttle requests, identify yourself, and handle failure modes explicitly instead of hammering retries.
You will be able to:
- Explain the request/response cycle and interpret status codes correctly
- Parse structured data out of HTML with BeautifulSoup selectors
- Page through a REST API with cursor or offset strategies and error retries
- Implement a rate limiter and robots.txt check before any crawl
- Decide legally and ethically whether a dataset may be collected at all
Prerequisites
- !Python requests or urllib basics
- !HTML document structure and CSS selectors
- !Turning JSON into a Pandas DataFrame
What You'll Learn
- 1Choose between an API, a bulk export, and a scraper for a given data need
- 2Write resilient fetch code with timeouts, retries, and backoff
- 3Extract tabular data from nested HTML without brittle XPath chains
- 4Document provenance and usage constraints for every external dataset
The request/response contract
Everything you collect over the web arrives as an HTTP response: a status code, headers, and a body. The status code is the first thing your code should branch on. 200 means success; 301/302 are redirects requests follows automatically by default; 401 and 403 mean authentication or authorization problems â not something a retry will fix; 404 means the resource is gone; 429 is the server telling you to slow down, and it usually carries a Retry-After header; 5xx is a server-side failure where a bounded retry with backoff is reasonable.
The second half of the contract is etiquette in headers. A descriptive User-Agent string with contact information lets operators identify and, if you are causing load, reach you. Timeouts must always be set â an unbounded requests.get that hangs forever will stall a notebook or an Airflow task until someone kills the worker. And never log or commit API keys; read them from environment variables.
| Status | Meaning | Your code should |
|---|---|---|
| 200 | OK | Parse the body |
| 301/302 | Redirect | Follow, but log unexpected redirect chains |
| 401/403 | Auth failure | Stop; refresh token or fix credentials |
| 404 | Not found | Stop for this URL; skip and continue the batch |
| 429 | Rate limited | Sleep for Retry-After, then retry a bounded number of times |
| 500/502/503 | Server error | Retry with exponential backoff, then give up |
Scraping HTML with BeautifulSoup
HTML from a real site is messier than any tutorial page: nested divs with generated class names, lazy-loaded sections, and prices split across spans. Robust scrapers key off stable attributes â itemcope microdata, data-* attributes, heading text â rather than nth-child positions that break on the next layout change.
import time
import requests
import pandas as pd
from bs4 import BeautifulSoup
BASE = "https://books.toscrape.com/catalogue/page-{}.html"
session = requests.Session()
session.headers.update({
"User-Agent": "ResearchBot/1.0 (contact: data-team@example.com)"
})
def fetch_page(page_num: int) -> BeautifulSoup:
url = BASE.format(page_num)
resp = session.get(url, timeout=15)
resp.raise_for_status()
return BeautifulSoup(resp.text, "html.parser")
def extract_books(soup: BeautifulSoup) -> list[dict]:
rows = []
for article in soup.select("article.product_pod"):
price_text = article.select_one("p.price_color").get_text(strip=True)
rating_class = article.select_one("p.star-rating")["class"][-1]
rows.append({
"title": article.select_one("h3 a")["title"],
"price": float(price_text.replace("ÂŖ", "")),
"rating_word": rating_class,
"availability": article.select_one("p.instock").get_text(strip=True),
})
return rows
records = []
for page in range(1, 6):
records.extend(extract_books(fetch_page(page)))
time.sleep(1.0) # polite delay between pages
df = pd.DataFrame(records)
print(df.head())
print(df["price"].describe())
Two details make this code production-grade: the session reuses TCP connections, and the explicit sleep after every page keeps requests-per-second in a range most sites tolerate. When a selector returns None unexpectedly, fail loudly on that row and collect the failure count rather than silently skipping, or you will ship a dataset with hidden holes.
Fetching structured data from REST APIs
APIs give you stable contracts â documented fields, versioning, and usually explicit pagination. Most analytics APIs paginate with either an offset parameter or a cursor token returned in the response. Cursors survive concurrent inserts; offsets can skip or duplicate rows when the underlying data changes mid-scan.
import os
import time
import requests
import pandas as pd
API = "https://api.example.com/v1/transactions"
HEADERS = {"Authorization": f"Bearer {os.environ['TX_API_KEY']}"}
def fetch_with_retries(url, params, max_attempts=4):
for attempt in range(1, max_attempts + 1):
resp = requests.get(url, headers=HEADERS, params=params, timeout=20)
if resp.status_code == 429:
wait = float(resp.headers.get("Retry-After", 2 ** attempt))
time.sleep(wait)
continue
if resp.status_code >= 500:
time.sleep(2 ** attempt)
continue
resp.raise_for_status()
return resp.json()
raise RuntimeError(f"Giving up on {url} after {max_attempts} attempts")
def fetch_all_pages(start_date: str, end_date: str) -> pd.DataFrame:
rows, cursor = [], None
while True:
params = {"start": start_date, "end": end_date, "limit": 500}
if cursor:
params["cursor"] = cursor
payload = fetch_with_retries(API, params)
rows.extend(payload["data"])
cursor = payload.get("next_cursor")
if not cursor:
break
time.sleep(0.5)
return pd.DataFrame(rows)
df = fetch_all_pages("2024-01-01", "2024-03-31")
print(len(df), df.columns.tolist())
Keep an eye on the payload shape: if the API caps page size at 500 and returns fewer, that is not automatically the last page â only a missing cursor (or an empty data list) signals completion. Record the extraction timestamp and the query parameters alongside the data so the snapshot can be reproduced or refreshed deterministically.
Rate limiting, robots.txt, and backoff
A rate limiter is not optional politeness; it is how you avoid becoming the reason a small site goes down. Space requests evenly, check robots.txt for the paths you intend to fetch, and back off aggressively on 429. The Python standard library ships a robots parser; wire it in before the first request of a crawl.
import time
from urllib.robotparser import RobotFileParser
def robots_allows(url: str, user_agent: str = "*") -> bool:
origin = "/".join(url.split("/")[:3])
rp = RobotFileParser()
rp.set_url(f"{origin}/robots.txt")
try:
rp.read()
except OSError:
return False # fail closed if robots.txt cannot be read
return rp.can_fetch(user_agent, url)
class TokenBucket:
def __init__(self, requests_per_second: float):
self.min_interval = 1.0 / requests_per_second
self._last = 0.0
def wait(self):
now = time.monotonic()
sleep_for = self._last + self.min_interval - now
if sleep_for > 0:
time.sleep(sleep_for)
self._last = time.monotonic()
bucket = TokenBucket(1.5)
for url in page_urls:
if not robots_allows(url, "ResearchBot/1.0"):
print(f"Skipping {url} â disallowed by robots.txt")
continue
bucket.wait()
# fetch and parse here
Fail closed when robots.txt is unreachable. A transient network blip should not become an accidental denial-of-service against a site that explicitly asked crawlers to back off.
Legal and ethical boundaries
Technical capability is not permission. Terms of service frequently forbid automated collection even for public pages; copyright covers the expression on the page, not just the underlying facts; and privacy regulations such as GDPR restrict collecting personal data from the open web into your own systems. Before a crawl project starts, answer these questions in writing: Is the data personal? Does the robots.txt or ToS prohibit this path? Is there a licensed or bulk alternative (government open data portals, provider APIs, academic corpora)? Who owns derived datasets inside your organization, and how long are they retained?
â ī¸When scraping is the wrong tool
Turning collections into analysis-ready tables
Scraped or API-fetched data rarely arrives analysis-ready: nested JSON needs flattening, inconsistent HTML needs cleaning, and records collected over multiple sessions need deduplication against a stable key. The final mile of any data collection pipeline is a normalization step that turns raw payloads into a tidy table with consistent types, a defined grain, and a timestamp for provenance.
Design that key early. For e-commerce pages it might be the product URL; for API responses, a cursor or id field. Without a stable key, incremental refreshes either duplicate rows or silently miss updates. Once the key exists, the rest is mechanical Pandas: explode nested lists, cast types, rename columns to your warehouse convention, and write to Parquet or CSV with the collection timestamp attached. This normalization step is what makes the difference between a folder of HTML files and a dataset you can actually analyze.
Whichever route you used, the handoff into analysis should be the same: normalize column names, enforce dtypes, deduplicate on a natural key, and write a provenance record.
import pandas as pd
def normalize(raw: pd.DataFrame, source: str) -> pd.DataFrame:
df = raw.copy()
df.columns = (
df.columns.str.strip()
.str.lower()
.str.replace(" ", "_", regex=False)
)
df["source"] = source
df["collected_at"] = pd.Timestamp.utcnow()
df = df.drop_duplicates()
return df
clean = normalize(df, "books.toscrape.com")
clean["price"] = pd.to_numeric(clean["price"], errors="coerce")
clean.to_csv("data/books_snapshot.csv", index=False)
print(clean.dtypes, len(clean))
That provenance pair â source string plus UTC timestamp â saves the next analyst (often you, three months later) from arguing with a mysterious CSV about where the numbers came from.