Lesson 35 of 41
Resilient Scraping: Pagination, Headers, Rate Limiting & Error Retries
Overview & Learning Objectives
Industrial data collection requires resilient web scrapers that can navigate multi-page pagination catalogs, recover from dropped sockets, and respect host infrastructure. Unregulated rapid scraping triggers IP bans, CAPTCHA challenges, and server overloads. Building production scrapers involves implementing respectful crawl delays with randomized jitter, rotating User-Agents, managing session cookies, and utilizing robust retry loops with exponential backoff.
- Automate multi-page catalog traversal using query parameter pagination and "Next Page" link tracking.
- Implement polite crawling mechanisms using `time.sleep()` with randomized jitter to prevent IP rate-limiting.
- Configure automated HTTP retry strategies using `urllib3.util.Retry` and `requests.adapters.HTTPAdapter`.
Industry Standard
Standard: Data scraping operations at Bloomberg and FactSet strictly enforce a minimum 1.5-second random crawl delay per domain and identify crawlers with clear business contact User-Agent headers.
Real-World Example: ScoopCraft Multi-Page National Wholesale Price Audit
ScoopCraft scrapes 50 pages of bulk dairy ingredient auctions, managing pagination termination and connection retries.
| Page Number | Records Ingested | HTTP Response | Crawl Delay | Status |
|---|---|---|---|---|
| Page 1 | 40 items | 200 OK | 1.8s delay | Completed successfully |
| Page 2 | 40 items | 200 OK | 2.3s delay | Completed successfully |
| Page 3 | 40 items | 503 Service Unavailable | Backoff 4.0s (Retry 1/3) | Recovered on retry |
| Page 51 | 0 items (End of Catalog) | 404 Not Found | 0.0s | Graceful exit loop |
Syntax & Core Code Implementation
import time
import random
import requests
from bs4 import BeautifulSoup
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
# Configure resilient session with exponential backoff
session = requests.Session()
retries = Retry(
total=3,
backoff_factor=1.5,
status_forcelist=[429, 500, 502, 503, 504]
)
session.mount('https://', HTTPAdapter(max_retries=retries))
all_products = []
page = 1
while True:
url = f'https://wholesale-dairy.internal/items?page={page}'
headers = {'User-Agent': f'ScoopCraftAnalytics/2.0 (analyst@scoopcraft.internal)'}
response = session.get(url, headers=headers, timeout=10)
if response.status_code != 200:
print(f"Stopping at page {page} (Status: {response.status_code})")
break
soup = BeautifulSoup(response.content, 'html.parser')
items = soup.select('.item-card')
if not items:
print(f"No items found on page {page}. Ingestion complete.")
break
for item in items:
all_products.append({
'name': item.select_one('.name').get_text(strip=True),
'price': item.select_one('.price').get_text(strip=True)
})
print(f"Ingested page {page}: {len(items)} items.")
page += 1
# Polite randomized delay (1.5s - 3.0s)
time.sleep(random.uniform(1.5, 3.0))
Parameters & Arguments Breakdown
backoff_factor: Multiplier for exponential pause between failed attempts (e.g. 1s, 2s, 4s).status_forcelist: HTTP response codes that trigger automatic retry attempts.random.uniform(a, b): Generates non-deterministic delay preventing predictable crawler signature detection.
Step-by-Step Implementation
- Mount Resilient Adapter: Configure `requests.Session` with `urllib3.util.Retry` for automatic transient fault handling.
- Construct Pagination Loop: Use `while True` loop that increments page index until no items are found or response is non-200.
- Inject Polite Delay: Add `time.sleep(random.uniform(1.0, 2.5))` at end of each loop iteration.
Common Mistakes & Limitations
- Using a fixed `time.sleep(1.0)` delay, which exhibits a robotic signature easily flagged by anti-bot firewalls.
- Scraping infinitely without a safety cap on maximum pages (`max_pages = 100`), risking infinite loops if the site returns duplicate content on invalid page numbers.
- Creating a new `requests.Session()` inside the loop instead of reusing one session instance across all pages.
Keyboard Shortcuts (Jupyter & VS Code)
| Action | Windows | Mac |
|---|---|---|
| Interrupt running scraper loop in terminal | Ctrl + C | Cmd + C |
Pro Tips & Modern Best Practices
- Always inspect the Network tab in DevTools first; many paginated websites fetch JSON data asynchronously via hidden API calls, allowing you to bypass HTML parsing entirely!
- Store scraping progress incrementally in SQLite or write rows immediately to CSV so interrupted runs can resume without restarting from page 1.