/research:scraping-engineering-pythonfrom research
Use when scaling a Python scraper beyond a single-file requests script — encodes Lawson's *Web Scraping with Python* engineering layer (caching to disk and MongoDB, concurrent downloading, dynamic content via WebKit/Selenium/Playwright, form interaction, CAPTCHA strategies, Scrapy framework selection).
Ships in research. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Drift-prone skill. Library APIs, headless-browser stealth techniques, and anti-bot countermeasures (Playwright/Selenium internals, CAPTCHA services, TLS-fingerprint tooling like
curl-cffi) change frequently as sites update detection. Verify current library versions and site behavior before promising a given approach still works.
| Input | Source/provider | If absent |
|---|---|---|
| Authorised targets, fields, volume, and freshness | Requester and target terms | Stop network execution and return a design plan. |
| Robots/politeness result and sample responses | Target and foundations check | Do not crawl until assessed. |
| Artifact | Consumer | Acceptance condition |
|---|---|---|
| Resumable Python pipeline | Operator | Restarts safely, honours limits, surfaces failures, and preserves provenance. |
| Data batch and manifest | Analyst | Schema, source, fetch time, failures, and selector version are recorded. |
| Category | Artifact | Acceptance condition |
|---|---|---|
| Correctness | Extraction and restart test | Fields and checkpoint recovery pass on representative pages. |
Review and design default to read-only. Network requests, account/session use, form submission, CAPTCHA handling, storage, or production execution require explicit authority. Never bypass access controls.
Without network, browser, storage, credentials, or permission, return reviewed code and a dry-run plan. Mark live behaviour unassessed.
| Choice | Action | Failure/risk avoided |
|---|---|---|
| HTTP/JSON path works | Exclude browser automation | Fragile runtime |
| Blocking or consent challenge | Stop and notify | Circumvention |
| Crawl must resume | Use durable checkpoints and idempotent writes | Duplicate records |
The pipeline is polite, bounded, restartable, observable, and tested on representative pages.
For an authorised resumable catalogue crawl, validate a cached sequential sample, add bounded concurrency and idempotent storage, then interrupt and restart without duplicates.
Encodes Richard Lawson's Web Scraping with Python (Packt) as the engine's engineering layer for production-grade Python scrapers. Pair with ../web-scraping-foundations/references/scraper-troubleshooting-and-etiquette.md (etiquette and debugging) and web-scraping-foundations (basics). For non-Python pipelines, the patterns transfer; the libraries change.
A single-file requests script is fine for one-off scrapes. Move to the patterns in this skill when any of the following holds:
Why: development iterations should re-parse cached responses, not re-fetch them. Caching also enables resumable crawls.
URL → safe filename mapping. Critical filesystem rules:
| OS | FS | Invalid chars | Max filename |
|---|---|---|---|
| Linux | Ext3/4 | /, \0 | 255 bytes |
| macOS | HFS+/APFS | :, \0 | 255 UTF-16 units |
| Windows | NTFS | `\ / ? : * " > < | ` |
import re, os, gzip, pickle
from urllib.parse import urlsplit
class DiskCache:
def __init__(self, cache_dir="cache"):
self.cache_dir = cache_dir
def url_to_path(self, url):
components = urlsplit(url)
path = components.path
if not path or path.endswith("/"):
path += "index.html"
filename = components.netloc + path + components.query
filename = re.sub(r'[^/0-9a-zA-Z\-.,;_ ]', '_', filename)
# cap each segment at 255 chars
filename = '/'.join(seg[:255] for seg in filename.split('/'))
return os.path.join(self.cache_dir, filename)
def __getitem__(self, url):
path = self.url_to_path(url)
if os.path.exists(path):
with gzip.open(path, "rb") as f:
return pickle.load(f)
raise KeyError(url)
def __setitem__(self, url, result):
path = self.url_to_path(url)
os.makedirs(os.path.dirname(path), exist_ok=True)
with gzip.open(path, "wb") as f:
pickle.dump(result, f)
When the disk-cache file count is the bottleneck (>1 M URLs), or you need cross-machine sharing, switch to MongoDB with the URL as _id and upsert=True:
from pymongo import MongoClient
from datetime import datetime, timedelta
class MongoCache:
def __init__(self, client=None, expires=timedelta(days=30)):
self.client = client or MongoClient("localhost", 27017)
self.db = self.client.cache
self.expires = expires
def __getitem__(self, url):
rec = self.db.webpage.find_one({"_id": url})
if rec is None:
raise KeyError(url)
if datetime.utcnow() - rec["timestamp"] > self.expires:
raise KeyError(f"{url} expired")
return rec["result"]
def __setitem__(self, url, result):
record = {"result": result, "timestamp": datetime.utcnow()}
self.db.webpage.update_one({"_id": url}, {"$set": record}, upsert=True)
Rules: every cache entry stores a timestamp; every read enforces TTL; expired entries trigger re-fetch (do not silently serve stale).
Three concurrency models, ranked by typical fit for scraping:
concurrent.futures.ThreadPoolExecutor) — best for I/O-bound HTTP; simple; default choice.httpx.AsyncClient, aiohttp) — highest throughput; steeper learning curve; required for >100 in-flight.from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch(session, url):
return url, session.get(url, headers=HEADERS, timeout=30)
with ThreadPoolExecutor(max_workers=10) as ex:
futures = [ex.submit(fetch, session, u) for u in urls]
for f in as_completed(futures):
url, response = f.result()
# process
Concurrency budget per host (the engine's politeness policy still applies):
| Site posture | Workers per host |
|---|---|
| Public API or sitemap-blessed | 5–10 |
| Standard public site | 2–3 |
Restrictive Crawl-delay | 1 (sequential) |
| You have written permission | per agreement |
Concurrency-per-host ≠ concurrency total. A pool of 50 hitting one host is rude; 50 hitting 50 distinct hosts is fine.
The page renders correctly in a browser but the HTML you fetch is empty. Options, ranked by efficiency:
<script> tag (__NEXT_DATA__, window.__INITIAL_STATE__). Extract it via regex or BeautifulSoup, parse it.| Tool | Strengths | Weaknesses |
|---|---|---|
| Playwright | Modern, fast, async, multi-browser, built-in network interception | Requires browser binaries |
| Selenium | Mature, language coverage | Slower; flakier; older API |
| PyQt WebKit (Lawson's choice) | Embedded in Python | Old; less maintained |
| Splash | HTTP API to Lua-driven browser | Extra service to run |
Playwright minimal example:
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page(user_agent=REAL_UA)
page.goto(url, wait_until="networkidle")
page.wait_for_selector("#result")
html = page.content()
browser.close()
Cost rule: a headless browser uses 100–500 MB and 1–3 s per page. Reserve for the pages that genuinely need it; never headless-render an entire crawl by reflex.
Three form-handling levels:
| Approach | When |
|---|---|
| Build the request manually | Static form, all fields in HTML, no JS validation |
mechanicalsoup / requests + BeautifulSoup | Form has hidden CSRF fields and standard HTML inputs |
| Browser automation (Playwright) | Form requires JS-driven clicks, AJAX submission, dynamic field reveal |
Always:
action URL with all hidden fields plus your own.Ranked by what to try first:
reCAPTCHA v3 / hCaptcha: practically un-bypassable without paid services or browser automation with a real session. If a target uses these, prefer official API access or written permission over technical defeat.
Scrapy is a full crawling framework. Choose it when the project has:
scrapy-redis).Stick with requests + your own loop when the project is a single spider for a single site with simple output.
Minimal Scrapy spider:
import scrapy
class ExampleSpider(scrapy.Spider):
name = "example"
start_urls = ["https://example.com/list"]
custom_settings = {
"DOWNLOAD_DELAY": 1.5,
"AUTOTHROTTLE_ENABLED": True,
"USER_AGENT": REAL_UA,
"ROBOTSTXT_OBEY": True,
"CONCURRENT_REQUESTS_PER_DOMAIN": 2,
}
def parse(self, response):
for href in response.css("a.detail::attr(href)").getall():
yield response.follow(href, self.parse_detail)
next_page = response.css("a.next::attr(href)").get()
if next_page:
yield response.follow(next_page, self.parse)
def parse_detail(self, response):
yield {
"title": response.css("h1::text").get(),
"price": response.css(".price::text").get(),
"url": response.url,
}
Scrapy settings to always set:
ROBOTSTXT_OBEY = TrueAUTOTHROTTLE_ENABLED = True with conservative AUTOTHROTTLE_TARGET_CONCURRENCYDOWNLOAD_DELAY ≥ 1.0RETRY_ENABLED = True, RETRY_TIMES = 3HTTPCACHE_ENABLED = True during developmentUSER_AGENT set to a real browser stringCONCURRENT_REQUESTS_PER_DOMAIN = 2| Output | Right format |
|---|---|
| <100 k rows, mostly read by humans | CSV |
| Tabular, repeated reads, mixed types | Parquet (columnar, typed, compressed) |
| Document/nested data | JSONL (one JSON per line; streamable) |
| Many appends, search needed | SQLite for single-user, PostgreSQL for multi-user |
| Page caches keyed by URL | MongoDB with TTL index, or filesystem |
Engine convention: scraped artefacts land as Parquet + JSONL alongside a manifest (source, fetched_at, headers, selector_versions, n_rows, n_errors). Pair with data-quality-pipeline to score each batch.
For Scrapy: enable JOBDIR (scrapy crawl example -s JOBDIR=jobs/example) — it persists the request queue and dupefilter to disk.
requests.get (hangs forever on slow servers).Retry-After from 429 responses.ROBOTSTXT_OBEY = False and no DOWNLOAD_DELAY.web-scraping-foundations/references/scraper-troubleshooting-and-etiquette.md — etiquette and debuggingweb-scraping-foundations — HTTP/HTML basicsscraping-politeness-and-ratelimiting — politeness layerdata-quality-pipeline — score scraped batchesmerge-discipline — joining scraped data with reference dataWhat SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub peterbamuhigire/chwezi-research-engine --plugin research59 skills in this plugin
/00-meta-initializationUse when starting a scaffolded research workspace that needs an explicit project profile, methodology, audience-output matrix, wave roadmap, and dispatch gate; do not use for routine work inside an already initialised project./academic-reporting-standardsUse when an academic paper, thesis, dissertation, journal article, systematic review, or examinable artefact must follow a named reporting or examination standard; use academic-writing instead for prose craft without a reporting-standard decision./academic-writingUse when drafting or revising an academic paper, essay, thesis, or dissertation with source-away composition, originality, citation, synthesis, voice, and register controls; use academic-reporting-standards for selecting formal study-reporting rules.