A single-read guide to the tool categories of modern web scraping — including the AI browser-agent category that rewrote the playbook in 2025, and the seven traps that quietly break production scrapers.
7 Pipeline stages
6 Tool categories
5 Decision questions
8 Production traps
New to scraping? Try extraction methods in this order
Work top to bottom — stop when one works. Most sites yield at step 1 or 2. Jump to the Concepts section for code on each.
Full guide: Pipeline → Decision Geometry → Tool Categories → Decision Flow → Production Traps → Concepts.
Chapter I — The Mental Model
A scraper is a pipeline, not a library.
Every scraper passes through these seven stages. Tools live at one or two of them. The mistake everyone makes is collapsing all seven into "scraping" and then comparing Scrapy to Playwright as if they were alternatives. They're not — they live at different stages.
01
Discover
Find URLs
02
Fetch
Get raw bytes
03
Render
Execute JS
04
Parse
HTML → tree
05
Extract
Pull fields
06
Store
Persist, dedupe
07
Orchestrate
Schedule, retry
Click any stage
Each stage has its own set of tools, tradeoffs, and failure modes. Try 04 · Parse or 07 · Orchestrate.
Chapter II — Locate Your Site
Three axes determine your stack.
Before picking a library, locate yourself in three dimensions. Every meaningful scraping decision is a point in this space — and most "should I use X or Y?" debates are arguments about the wrong axis.
→ Data Location
Is the data in initial HTML, rendered by JS, behind interaction, or wildly varied across sites? Determines whether you need a browser.
↑ Anti-Bot Pressure
Open sites need nothing. Friction sites need proxies and delays. Fortress sites (Cloudflare, Datadome) need residential IPs + stealth.
↗ Maintenance Appetite
Hand-wired control, framework defaults, or pay-to-skip. Pushes you up the build→buy ladder of tool categories regardless of the other two axes.
Chapter III — Choose & Compose Your Stack
Pick by stage, not by category.
A scraper is 2–4 tool categories stacked. Most confusion — "Playwright vs Scrapy?", "Browserbase vs Browser Use?" — comes from comparing tools that fill different stages. They're not alternatives. Here's the full map.
The shape of every scraper
One spine you climb only when forced — plus one add-on when volume is high, and one bypass if you'd rather pay. Remember that sentence and you have this chapter. The six categories aren't a flat menu; they play three different roles.
① The spine — climb only when the rung below fails
1Data already in the HTML (or a hidden JSON/XHR API)?
→ Building Blocks · httpx + parsercheapest · try first
Frameworks — Scrapy, Crawlee. Bolt onto any spine rung once you hit ~10k+ pages on a schedule: queue, retry, dedupe, rate-limit for free. Not harder fetching — orchestration.
③ The bypass pay to skip
Managed APIs — Firecrawl, Jina. Skip the spine entirely: URL in, clean data out, ~$0.001–0.01/page. Great for prototypes and <100k pages/month; the bill grows with volume.
See the full stack as one map
Shortcut — skip everything below
Managed Extraction APIs
URL in, clean structured data out. No setup, no infrastructure. Best for <100k pages/month or fast prototypes.
FirecrawlJina ReaderDiffbot
— or build your own stack, stage by stage —
OptionalAI Agent
Browser UseStagehandSkyvern
LLM reads the page and decides what to click or extract. Add this when you have many different site layouts and selectors keep breaking.
↓ drives
OptionalOrchestration
ScrapyCrawleeplain script
Queue, retry, dedupe, rate-limit. Earns its keep above 10k pages. A plain script is fine for anything smaller.
↓ coordinates
RequiredFetch + Renderpick one →
httpxparsellxml
Static HTML — 50–100× faster, no cost. Try this first. Check the Network tab for a hidden XHR before reaching for a browser.
or
Playwrightpatchrightcamoufox
JS-rendered pages. Use when disabling JavaScript makes the page blank and there's no XHR to call directly.
↓ runs on · Playwright only
OptionalInfrastructurepick one →
Local Chrome
Free. Works until the site fingerprints your browser or IP range.
or
BrowserbaseHyperbrowserSteel
Cloud Chrome + residential proxies + stealth. Same Playwright code — different where Chrome runs.
Where the tree lands you — four common stacks
Each recipe is where the decision tree above drops you. Pick the simplest that matches; add categories only when you need them.
AStatic scraper
Data is in the initial HTML. No JS required. No heavy bot protection.
Fetchhttpx async
Extractparsel — CSS selectors or JSON-LD
ScaleScript → Scrapy when >10k pages
BJS-rendered pages
Page goes blank without JS. No accessible XHR endpoint. Moderate or no bot protection.
Fetch+RenderPlaywright + patchright
ExtractPlaywright locators or parsel
ScaleScrapy or Crawlee
CFortress site
Cloudflare / Datadome / Akamai wall. Local browsers get fingerprinted and blocked.
Fetch+RenderPlaywright + patchright
InfraBrowserbase — cloud + residential proxies
ChallengesSolver service (CapSolver / 2Captcha) for captcha · proof-of-work
ScaleScrapy or Crawlee
DVaried or agentic
Many different site layouts, or task needs navigation + form-filling + extraction in sequence.
AgentBrowser Use or Stagehand
Fetch+RenderPlaywright
InfraBrowserbase
Tool Reference
Reference, not reading — expand a category only when you'll actually use it.
Open the detailed tool reference — 6 categories, with code
How to scan: match "When to use" to your situation, read the picks and code, skip the rest.
01
Building Blocks
HTTP + parser, hand-wired.
SPEED · fastest
COST · $0
STAGE · fetch + parse
When to use
Data is in the initial HTML response
You want full control over each request
You're scraping a single, well-structured site
When not to
Page needs JavaScript to populate
You'd reinvent retry / queue / dedupe logic
Top picks
httpxAsync HTTP, modern default
parselScrapy's parser, lxml speed + clean API
lxmlXPath support, very fast
selectolaxFastest HTML parser, CPU-bound jobs
→ Real code · JSON-LD first, selector fallback
Python
import httpx, json
from parsel import Selector
r = httpx.get("https://example.com/product/123", timeout=10)
sel = Selector(text=r.text)
# Try JSON-LD first — free, structured, SEO-maintainedfor script in sel.css('script[type="application/ld+json"]::text'):
data = json.loads(script.get())
if data.get("@type") == "Product":
print(data["name"], data["offers"]["price"])
breakelse:
# Fallback to selectors only if JSON-LD missing
name = sel.css("h1.product-title::text").get()
price = sel.css(".price::text").get()
02
Browser Automation
When the page won't render without JavaScript.
SPEED · 50–100× slower
COST · RAM-heavy
STAGE · render
When to use
Disabling JS makes the page go blank
You need to click / scroll / wait for hydration
No underlying API exists in the Network tab
When not to
The page populates via an XHR you can call directly
RAM + concurrency budget is tight (~500MB each)
Top picks
PlaywrightModern default · async · auto-wait
patchrightStealth-patched Playwright fork
camoufoxFingerprint-evading Firefox build
→ Real code · Playwright async
Python
from playwright.async_api import async_playwright
async withasync_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.goto("https://example.com/products")
await page.wait_for_selector(".product-card")
cards = await page.query_selector_all(".product-card")
for card in cards:
name = await (await card.query_selector(".name")).inner_text()
print(name)
await browser.close()
StagehandTypeScript · built by Browserbase · act/extract/observe
SkyvernVision-based · no selectors · resilient to redesigns
→ Real code · Browser Use with natural language
Python
from browser_use import Agent
from langchain_anthropic import ChatAnthropic
agent = Agent(
task=(
"Go to example.com/products. ""Find all items under $50. ""Return name and price as JSON."
),
llm=ChatAnthropic(model="claude-sonnet-4-5"),
)
result = await agent.run()
print(result.final_result)
Composition — how the stack fits together
Tool categories stack. Most production scrapers use three.
A common point of confusion: "Browserbase vs Browser Use vs Playwright — which is best?" Wrong question. They're three different categories filling different stages of the same stack. Here's how they actually compose.
Read top-to-bottom: a task flows down through reasoning, driving, and infrastructure to reach the site. Each category can be swapped independently.
Choose categories, not products. A site change usually only forces you to swap one — keeping the others reduces blast radius.
Converge — or let the guide pick your stack
Five questions, in this order.
Answer in sequence. The output is a recommended stack with the specific tools and what to watch for. Re-run it for each project; the answers shift more than you'd expect.
Chapter IV — Traps in Production
Eight traps that quietly break scrapers.
Each of these costs roughly a month of debugging to learn the hard way. Read them now and save yourself the tuition.
01
Reaching for a browser before checking for an API.
Open DevTools → Network → XHR. The page rendering with JavaScript is almost always calling a JSON endpoint internally. Hitting that endpoint with httpx is faster, cheaper, more stable, less detectable. Browsers should be the last resort, not the first reach.
02
Skipping JSON-LD entirely.
SYMPTOM · Hand-written selectors for fields already structured
Roughly 80% of e-commerce sites publish schema.org/Product as JSON-LD in the page head — the site owner maintains it for SEO. Free, structured, durable. Always try JSON-LD first. Selectors second. LLM extraction last.
03
Sync HTTP at scale.
SYMPTOM · 10-hour jobs that should be 6 minutes
A sync scraper spends 95% of its time blocked on network. Switching requests for httpx async and firing 100 concurrent calls is the single biggest performance win available, and the code is almost identical.
04
Vanilla Playwright on protected sites.
SYMPTOM · "Just a moment..." Cloudflare page · empty results
Default Chromium has tell-tale fingerprints (navigator.webdriver, missing plugins, CDP traces) that Datadome and Cloudflare detect in milliseconds. You need patchright, camoufox, or a managed stealth browser. And the trap runs deeper than the browser: plain HTTP clients are fingerprinted at the network layer too (TLS/JA4, HTTP/2), so a bare httpx call is just as visible — for direct API hits under pressure, reach for a TLS-impersonating client (curl_cffi). The deeper rule: anti-bot scores every layer together — TLS, headers, JS, IP, timezone — so a spoofed user-agent over a Python TLS fingerprint is more detectable, not less. Present one coherent identity across all layers, or none.
05
Datacentre proxies on serious sites.
SYMPTOM · Cheap proxies that get blocked instantly
AWS, GCP, DigitalOcean IPs are pre-flagged by every major anti-bot vendor. Residential and ISP proxies (Bright Data, Oxylabs, Smartproxy) cost $5–$15 per GB, and that's the line item you can't skip. Budget for it on day one, not month two.
06
Cancel-as-insert ghost rows.
SYMPTOM · Duplicate records · phantom inventory · "off-by-one" reports
Many source systems model cancellations or refunds as inserts of a new row instead of updates to the original. Naive incremental scrapers see both rows as real and inventory or counts double. Always check the source's update semantics before trusting any incremental refresh.
07
Treating LLM extraction as primary.
SYMPTOM · $2k/month bills for what selectors do for $0
LLMs are seconds-per-page and cents-per-call. Selectors are microseconds and free. The right pattern: deterministic methods first, LLM only on novelty. Even better — capture the selector path the LLM implicitly used and reuse it next time. Self-healing selectors collapse your cost.
08
Anti-bot drift.
SYMPTOM · Scraper that worked in March returns empty pages in June
Stealth patches age. Fingerprint surfaces shift. Detection vendors update weekly. A scraper that ran clean in spring will silently start returning empty pages in summer. Build monitoring (success rate per domain, response-size distribution, captcha-encounter rate) into the pipeline from day one. Drift is the rule, not the exception.
Chapter V — Find Your Data · Extracting Fields
Five ways to extract fields from a page.
This is the Extract ladder — pulling fields out of a page you already have. (Finding the page's URL in the first place is a different problem — Discover, the next chapter.) Try these in order; each that works lets you skip everything below. Most scrapers never pass step three.
Try in order →01Network / XHR→02JSON-LD→03CSS Selectors→04XPath→05ARIA Locators
Try01First
Network / XHR
Before writing any parsing code, check whether the page fetches its data from a hidden JSON API. If it does, you can call that endpoint directly — no HTML, no selectors, no browser needed. This is almost always the cleanest data you'll find.
How to spot it
Open DevTools → Network tab
Filter to Fetch / XHR
Reload — watch for JSON responses
Click a request → Response tab to inspect it
If it has your data: right-click → Copy as cURL
Use when
Fetch/XHR calls appear in DevTools
Response is structured JSON
Pagination is a query parameter
Skip when
No XHR visible — data is server-rendered HTML
Endpoint requires rotating session tokens
Call the endpoint directly (no browser)
Python
import httpx
# Copy headers from DevTools → request headers
r = httpx.get(
"https://example.com/api/v2/products",
params={"page": 1, "limit": 50},
headers={
"accept": "application/json",
"x-requested-with": "XMLHttpRequest",
},
)
for item in r.json()["data"]:
print(item["name"], item["price"])
Many sites — especially e-commerce — embed perfectly structured data in a <script type="application/ld+json"> tag for search engines. That same data is free for you to read. No selector needed — just json.loads().
How to spot it
DevTools → Elements → search ld+json. Look for a JSON object with "@type": "Product", "Article", "Recipe", etc.
Common schema.org types
Type
Typical page
Key fields
Product
e-commerce PDP
name, offers.price, sku
Article
news / blog
headline, author, datePublished
Recipe
food site
name, recipeIngredient, cookTime
BreadcrumbList
any
itemListElement[].name
Event
event listings
name, startDate, location
Why it outlasts selectors
Structured — no guessing element positions
SEO-maintained by site owner, stays accurate
Survives CSS and layout redesigns
Extraction pattern (parsel)
Python
import httpx, json
from parsel import Selector
r = httpx.get("https://example.com/product/42")
sel = Selector(text=r.text)
for blob in sel.css(
'script[type="application/ld+json"]::text'
).getall():
data = json.loads(blob)
if data.get("@type") == "Product":
name = data["name"]
price = data["offers"]["price"]
sku = data.get("sku", "")
print(name, price, sku)
break
Try03Third
CSS Selectors
The workhorse of web scraping. CSS selectors target HTML elements by tag, class, ID, or attribute. They work on static HTML without a browser — fast and cheap. Most scrapers live here.
Core syntax
Selector
Matches
div
Any <div> element
.card
class includes "card"
#main
id="main"
[data-id="42"]
data-id equals "42"
div.card
<div> that also has class card
ul > li
Direct <li> children of <ul>
h2 + p
<p> immediately after <h2>
:nth-child(2n)
Every even child
parsel extras (not standard CSS)
Selector
Returns
h1::text
Text content of <h1>
a::attr(href)
Value of href attribute
parsel example
Python
import httpx
from parsel import Selector
r = httpx.get("https://example.com/products")
sel = Selector(text=r.text)
for card in sel.css(".product-card"):
name = card.css("h3::text").get()
price = card.css(".price::text").get()
url = card.css("a::attr(href)").get()
print(name, price, url)
Playwright CSS extras
Python
# Playwright adds :has-text(), :visible, :has()
in_stock = page.locator(
".product-card:has-text('In stock'):visible"
)
print(await in_stock.count())
# Attribute selectors — more stable than generated class names
items = page.locator("[data-product-id]")
async for item in items.all():
pid = await item.get_attribute("data-product-id")
print(pid)
Avoid class names like sc-a7f3b — they change every deploy. Prefer [data-*] attributes or structural selectors.
Try04Fourth
XPath
XPath is a full query language for HTML trees. Reach for it when CSS falls short: selecting elements by text content, traversing up to a parent, or picking table cells by their header name.
Syntax reference
Expression
Meaning
//div
Any <div> anywhere in the document
@href
The href attribute value
text()
Direct text nodes of the element
[@class='card']
Exact class attribute match
[contains(@class,'card')]
Class contains "card"
[contains(text(),'Price')]
Text contains "Price"
[1] / [last()]
First / last match
parent::div
Nearest <div> parent
ancestor::article[1]
Nearest <article> ancestor
following-sibling::dd[1]
First <dd> after this node
When CSS can't, XPath can
Selecting a parent or ancestor element
Matching by visible text (text()='...')
Table cells selected by header name
parsel example
Python
from parsel import Selector
sel = Selector(text=html)
# Select by text — CSS can't do this natively
price = sel.xpath(
'//dt[contains(text(),"Price")]''/following-sibling::dd[1]/text()'
).get()
# Walk UP to the containing card
sold_out = sel.xpath(
'//span[text()="Sold Out"]/ancestor::article[1]'
)
for card in sold_out:
print(card.xpath('.//h3/text()').get())
# Attribute extraction
hrefs = sel.xpath('//a[@rel="nofollow"]/@href').getall()
Playwright XPath
Python
# Prefix with "xpath=" in Playwright locators
heading = await page.locator("xpath=//h1").inner_text()
# Table cell selected by header text
cell = page.locator(
"xpath=//th[text()='Price']/following-sibling::td[1]"
)
print(await cell.inner_text())
Try05Playwright
ARIA & Role Locators
Playwright's get_by_* methods find elements by what they mean — role, label, visible text, or placeholder — not how they look. They survive CSS refactors and are Playwright's recommended default for form interactions and navigation.
get_by_* methods
Method
Finds by
get_by_role("button", name="Submit")
ARIA role + accessible name
get_by_label("Email")
<label> text or aria-label attr
get_by_text("Add to cart")
Any visible text content
get_by_placeholder("Search...")
Input placeholder
get_by_alt_text("Logo")
Image alt attribute
get_by_test_id("submit-btn")
data-testid attribute
Locator precedence rule
1st:get_by_role — most semantically stable
2nd:get_by_label / get_by_text
3rd:get_by_test_id — needs eng cooperation
Last: CSS / XPath — only when above won't work
Login + navigation example
Python
from playwright.async_api import async_playwright
async withasync_playwright() as p:
page = await (
await p.chromium.launch()
).new_page()
await page.goto("https://example.com/login")
# Form — survives CSS refactorsawait page.get_by_label("Email").fill("user@example.com")
await page.get_by_label("Password").fill("secret")
await page.get_by_role(
"button", name="Sign in"
).click()
await page.wait_for_url("**/dashboard")
h1 = await page.get_by_role(
"heading", level=1
).inner_text()
print(h1)
# Nav links — chain locators
nav = page.get_by_role("navigation")
for link inawait nav.get_by_role("link").all():
print(await link.inner_text())
Chapter VI — Discover · Finding the URL
You can't fetch a URL you don't have.
Most guides start at Fetch and assume a URL in hand. Often you don't have one — you have an identity (a name, an address, a registration number) and must find the site first. That's Discover, pipeline stage 1, and it's where enrichment projects actually begin.
From identity → website — three hops
1Resolve a clean identity
name + address + state. A business register (e.g. ABN Lookup) fills gaps and canonicalises the name — it returns identity + location, not a website.
2Find a candidate site
search name + address + state — a maps/places API returns the official site directly (its website field); a web-search API gives the top organic result. Search the name + location, never the registration number — a number has nothing to match on.
3Verify it's the right one
does the page mention the name and match the suburb / postcode? A multi-signal match is the accept test — and the step people skip, where wrong data enters.
When the business is gone — a trust-ordered fallback
A defunct business may have no live site. Don't fail — climb a fallback chain, and tag how far down you had to go as provenance.
1Its own site, still live?
→ use ithighest trust
2An archived snapshot?
→ fetch the old homepage from a web archive (Wayback Machine)high
3A parent company?
→ resolve the parent's site and infer from itlower · holding-co risk
↳ a diversified parent's industry ≠ the subsidiary's — mark provenance "inferred from parent"
4Nothing left?
→ infer from name + address text alonelowest · flag it
Stack note: Discover is search/API-heavy on open sites — it lives on the cheapest spine rung (a places/search API + httpx + a parser). No browser or stealth needed. Cache results per entity; a false match is the costly failure, so verification (hop 3) is not optional.