跳到正文
DEV Community· Mango Developer·· 4 小時前AI 評分47

如何擴展 Playwright 爬蟲:從單頁到每小時一百萬次請求

How to Scale Playwright Scrapers: From One Page to a Million Requests an Hour

AI 導讀

文章説明如何把 Playwright 爬蟲由單頁擴展至每小時一百萬次請求,涵蓋瀏覽器上下文池、Redis 工作佇列、代理輪換、重試及跨機器擴展。建議先檢查頁面能否用 httpx 擷取資料,只有需要瀏覽器渲染時才使用 Playwright。

正文

The first time I tried to scrape a price-comparison site at scale, I fired up a Playwright loop, pointed it at 50,000 product pages, and let it rip. Within eight minutes my IP was banned. Within twenty minutes, my cloud provider sent me a polite email suggesting I read their acceptable use policy. I learned two things that day: rate limits are real, and the difference between "a script that scrapes one page" and "a scraper that survives at scale" is about two orders of magnitude of engineering.

Playwright is the best browser-automation library available right now. It's faster than Selenium, more capable than Puppeteer (same multi-browser engine, better API), and the async Python implementation is genuinely good. But the out-of-the-box experience is "open one browser, scrape one page." Real scraping needs a pool of browsers, a queue of work, rotating proxies, request interception to skip the junk that bloats your bill, retry logic that handles transient failures without re-scraping successful pages, and a way to scale across multiple machines without re-scraping the same URL twice.

This is the article I wish I'd had the first time I tried to scale a scraper and watched it fall over.

What Playwright Actually Is (and When to Use It)

Playwright is a Node.js and Python library that drives real browsers (Chromium, Firefox, WebKit) via the DevTools protocol. It can render JavaScript, handle SPAs, click buttons, fill forms, and extract content exactly as a user would see it. Compared to alternatives:

Tool Language Browser Speed Stealth Best for
Playwright JS/Py/Java/.NET All 3 Fast Good Modern SPAs, multi-browser
Puppeteer JS/Py (port) Chromium Fast Good JS shops, Chromium-only
Selenium Multi All Slow Poor Legacy test suites
Scrapy Python None (HTML) Very fast N/A Static HTML, no JS
browserless Hosted Chromium Fast Good Managed infrastructure
Bright Data Managed All Fast Excellent Enterprise, expensive

The decision tree: if the page renders server-side and you can parse the HTML, use Scrapy or httpx + BeautifulSoup. You'll be 100x faster and 100x cheaper. If the page is a React/Vue/Svelte SPA that loads data via XHR after rendering, you need a browser, and Playwright is the answer. Don't reach for Playwright until you've confirmed httpx can't do the job - running 50 browser instances to scrape static HTML is malpractice.

The threshold I use: if I can find the data in the page's network requests (DevTools → Network), I can usually replay those XHR calls with httpx and skip the browser entirely. Look at the network tab before you reach for Playwright. Most "JS-heavy" pages are actually "JS-heavy to render, but the data comes from a clean JSON API."

Prerequisites

  • Python 3.11+ (3.12 preferred for the asyncio improvements).
  • Playwright installed: pip install playwright && playwright install chromium.
  • An async mindset. Playwright's async API is the only sensible path at scale; the sync API blocks on every operation and you can't parallelize.
  • An asyncio understanding. If you've never written async def / await, spend an afternoon with the asyncio docs first.
  • A target you're allowed to scrape. Read the site's ToS. Respect robots.txt. Don't scrape personal data. The legal landscape around scraping is unsettled; the technical landscape is what this article covers.
  • A proxy provider for anything beyond a few hundred requests. We'll cover this below.

Install Playwright and its browsers:

BashCopy

python3 -m venv .venv && source .venv/bin/activate
pip install playwright httpx aiofiles tenacity redis
playwright install chromium
playwright install-deps # Linux only - installs system libs Chromium needs

For Docker, the official Playwright image already has browsers and deps:

BashCopy


shell
docker pull mcr.microsoft.com/playwright/python:v1.45.0-jammy


markdown

Architecture: From Single Page to Distributed

A scraping system at scale has four pieces:

CodeCopy


plaintext
┌──────────────────────────────────────────────────────────────────────┐
│ URL FRONTIER (Redis) │
│ pending: [url1, url2, url3, ...] done: {url: result_hash} │
│ failed: {url: retry_count} │
└──────────────────────────┬───────────────────────────────────────────┘
│ BLPOP / pipeline
┌──────────────────┼──────────────────┐
▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Worker 1 │ │ Worker 2 │ │ Worker N │
│ (asyncio) │ │ (asyncio) │ │ (asyncio) │
│ │ │ │ │ │
│ ┌──────────┐ │ │ ┌──────────┐ │ │ ┌──────────┐ │
│ │ Browser │ │ │ │ Browser │ │ │ │ Browser │ │
│ │ pool │ │ │ │ pool │ │ │ │ pool │ │
│ │ (N ctxs) │ │ │ │ (N ctxs) │ │ │ │ (N ctxs) │ │
│ └──────────┘ │ │ └──────────┘ │ │ └──────────┘ │
│ + proxy rot │ │ + proxy rot │ │ + proxy rot │
└──────┬───────┘ └──────┬───────┘ └──────┬───────┘
│ │ │
└──────────────────┼──────────────────┘
▼
┌─────────────────────────┐
│ STORAGE (S3 / Postgres) │
│ + dedup by content hash │
└─────────────────────────┘


markdown

  • URL frontier: a queue (Redis list) of URLs to scrape, plus a "done" set so workers don't re-scrape.
  • Workers: N processes, each running M async browser contexts. Each worker pulls from the queue, scrapes, stores results, marks URL done.
  • Browser pool: each worker manages a pool of browser contexts (not separate browsers - one browser with N contexts is far cheaper than N browsers).
  • Proxy rotation: each context uses a different proxy from a rotating pool.
  • Storage: results go to S3 / Postgres / wherever, deduplicated by URL + content hash so re-scrapes don't double-count.

The scaling axes are: more contexts per worker (CPU/RAM bound), more workers per machine (CPU bound), more machines (network/proxy bound). Most workloads peak around 4-8 contexts per worker, 2-4 workers per machine, then horizontal scale.

A Single-Page Scraper, Done Right

Start with the basics - a single page, scraped cleanly. This is the unit you'll parallelize.

PythonCopy


python

scrape_one.py

import asyncio
import json
from pathlib import Path
from playwright.async_api import async_playwright

async def scrape_product(url: str) -> dict:
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
context = await browser.new_context(
user_agent=(
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
),
viewport={"width": 1920, "height": 1080},
locale="en-US",
)
page = await context.new_page()

# Block non-essential resources to save bandwidth and time
async def block_junk(route):
if route.request.resource_type in {"image", "media", "font"}:
await route.abort()
else:
await route.continue_()

await page.route("*/", block_junk)

response = await page.goto(url, wait_until="domcontentloaded", timeout=30000)
if response is None or response.status >= 400:
raise RuntimeError(f"Failed to load {url}: status={response.status if response else 'None'}")

# Wait for the price element to render (SPA)
try:
await page.wait_for_selector('[data-testid="product-price"]', timeout=10000)
except Exception:
raise RuntimeError(f"Price selector not found on {url}")

data = await page.evaluate("""
() => {
const q = (sel) => document.querySelector(sel)?.textContent?.trim();
return {
title: q('h1.product-title'),
price: q('[data-testid="product-price"]'),
availability: q('[data-testid="availability"]'),
sku: q('[data-testid="sku"]'),
};
}
""")

await context.close()
await browser.close()
return {"url": url, **data}

if name == "main":
result = asyncio.run(scrape_product("https://example-shop.test/products/123"))
print(json.dumps(result, indent=2))


markdown

Three things to notice. First, request interception: we abort image, media, and font requests. On a media-heavy e-commerce page, this cuts bandwidth 80% and load time 50%. You don't need product images to scrape the price. Second, explicit selector waits: wait_for_selector is the right synchronization primitive, not time.sleep(2). Sleeping is what kills scraper throughput. Third, closing the context and browser: leaking contexts is the #1 cause of "my scraper's memory grows until OOM" issues. Always use async with or explicit close in a finally block.

The wait_until="domcontentloaded" parameter is also load-bearing. The default is "load", which waits for all resources including ads and tracking pixels. "domcontentloaded" fires when the DOM is ready; "networkidle" waits for 500ms of no network activity (good for SPAs, slow for ad-heavy pages). Pick based on the page.

The Browser Pool: Stop Launching a Browser Per Page

Launching a browser takes ~500ms and ~150 MB of RAM. If you do this per page, you're spending more time launching browsers than scraping. The fix is a browser pool: launch one browser, create N contexts, reuse them.

PythonCopy


python

browser_pool.py

import asyncio
from contextlib import asynccontextmanager
from playwright.async_api import async_playwright, BrowserContext

class BrowserPool:
"""Pool of reusable browser contexts.

One browser, N contexts. Each context is independent (cookies, storage).
"""

def init(self, size: int = 4, headless: bool = True):
self.size = size
self.headless = headless
self._playwright = None
self._browser = None
self._contexts: asyncio.Queue[BrowserContext] = asyncio.Queue(maxsize=size)
self._all_contexts: list[BrowserContext] = []

async def start(self) -> None:
self._playwright = await async_playwright().start()
self._browser = await self._playwright.chromium.launch(
headless=self.headless,
args=[
"--disable-blink-features=AutomationControlled",
"--no-sandbox",
"--disable-dev-shm-usage", # critical in Docker
"--disable-gpu",
],
)
for _ in range(self.size):
ctx = await self._browser.new_context(
user_agent=(
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
),
viewport={"width": 1920, "height": 1080},
locale="en-US",
java_script_enabled=True,
)
# Hide the webdriver property - basic anti-bot check
await ctx.add_init_script("""
Object.defineProperty(navigator, 'webdriver', {get: () => undefined});
Object.defineProperty(navigator, 'languages', {get: () => ['en-US', 'en']});
Object.defineProperty(navigator, 'plugins', {get: () => [1, 2, 3, 4, 5]});
""")
await self._contexts.put(ctx)
self._all_contexts.append(ctx)

@asynccontextmanager
async def acquire(self):
ctx = await self._contexts.get()
try:
yield ctx
finally:
# Clean cookies/storage so the next job starts fresh
await ctx.clear_cookies()
try:
await ctx.clear_permissions()
except Exception:
pass
await self._contexts.put(ctx)

async def stop(self) -> None:
for ctx in self._all_contexts:
await ctx.close()
if self._browser:
await self._browser.close()
if self._playwright:
await self._playwright.stop()


plaintext

Use it:

PythonCopy


python

main.py

import asyncio
from browser_pool import BrowserPool

async def scrape(pool: BrowserPool, url: str) -> dict:
async with pool.acquire() as ctx:
page = await ctx.new_page()
await page.goto(url, wait_until="domcontentloaded", timeout=30000)
# ... scrape ...
content = await page.content()
await page.close()
return {"url": url, "html": content[:1000]}

async def main(urls: list[str]):
pool = BrowserPool(size=4)
await pool.start()
try:
sem = asyncio.Semaphore(4) # max 4 concurrent scrapes
async def bounded(url):
async with sem:
return await scrape(pool, url)
results = await asyncio.gather(*[bounded(u) for u in urls], return_exceptions=True)
return results
finally:
await pool.stop()

if name == "main":
urls = [f"https://example.test/page/{i}" for i in range(50)]
asyncio.run(main(urls))


markdown

The semaphore plus the pool gives you controlled concurrency: at most N scrapes in flight, each using a context from the pool. If the pool is empty, acquire() blocks until one frees up. This is the foundation of all real scraping systems.

Request Interception: Don't Download What You Won't Use

Real pages load a stunning amount of garbage. A typical e-commerce product page loads 5 MB of images, 2 MB of JavaScript, 1 MB of fonts, and 200 KB of the actual content you want. Request interception lets you abort the junk.

PythonCopy


python
async def block_route(route):
rt = route.request.resource_type
url = route.request.url

# Abort resource types we never need
if rt in {"image", "media", "font"}:
await route.abort()
return

# Abort known analytics/tracking domains
if any(d in url for d in [
"google-analytics.com", "googletagmanager.com",
"doubleclick.net", "facebook.net", "hotjar.com",
"segment.io", "mixpanel.com", "fullstory.com",
]):
await route.abort()
return

# Pass everything else through
await route.continue_()

await page.route("*/", block_route)


plaintext

For static scraping where you only need the initial HTML, abort JS too:

PythonCopy


python
if rt == "script" and not url.startswith("https://target-site.com"):
await route.abort()


markdown

The savings are dramatic. On a recent e-commerce scrape, blocking images and third-party JS cut average page load from 4.2s to 0.9s - a 4.6x throughput improvement. Block aggressively; unblock only when something breaks.

Proxy Rotation: Don't Get Banned

If you scrape more than a few hundred requests from a single IP, you will get banned. There's no technical trick that prevents this - sites log IPs and rate-limit. The only solution is to rotate IPs.

Three proxy tiers exist:

Tier Cost Quality When to use
Datacenter $0.5-2/GB Poor (easily detected) Cheap testing, sites that don't block
Residential $5-15/GB Good Most production scraping
Mobile $20-50/GB Excellent Hardest targets (Google, Instagram)

For each request, pick a proxy from your pool. If a request fails with 403/429, mark that proxy as "tired" and try a different one:

PythonCopy


python

proxy_pool.py

import asyncio
import random
import time
from collections import defaultdict

class ProxyPool:
def init(self, proxies: list[str], cooldown_seconds: int = 300):
self.proxies = proxies
self.cooldown = cooldown_seconds
self._tired_until: dict[str, float] = defaultdict(float)
self._lock = asyncio.Lock()

async def get(self) -> str | None:
async with self._lock:
now = time.time()
available = [p for p in self.proxies if self._tired_until[p] < now]
if not available:
# All tired - return the soonest-available
return None
return random.choice(available)

async def mark_tired(self, proxy: str) -> None:
async with self._lock:
self._tired_until[proxy] = time.time() + self.cooldown
print(f"Proxy {proxy} cooled down for {self.cooldown}s")

Wire into context creation:

async def make_context_with_proxy(browser, proxy_pool: ProxyPool):
proxy = await proxy_pool.get()
if proxy is None:
raise RuntimeError("No proxies available - all cooling down")
ctx = await browser.new_context(
proxy={"server": proxy},
# ... other options ...
)
return ctx, proxy


plaintext

For serious scraping, use a proxy service that rotates IPs automatically (Bright Data, Oxylabs, Smartproxy, Soax). You connect to a single endpoint and the service gives you a new IP per request. Costs more but eliminates the rotation logic:

PythonCopy


python
ctx = await browser.new_context(
proxy={
"server": "http://rotating.bright-data.com:22225",
"username": "your-customer-id-zone-password",
"password": "session-12345", # change session to change IP
}
)


markdown

The session-12345 part is the trick - keep it constant for one session (one IP per session), change it for a new IP. Use the same session across all requests in one scrape job to maintain cookies; rotate sessions between jobs.

Stealth: Avoiding Headless Detection

Modern anti-bot systems (Cloudflare, Datadome, PerimeterX) detect headless browsers via a stack of tells: the navigator.webdriver property, missing Chrome properties, WebGL fingerprint, canvas fingerprint, and behavioral signals (mouse movements too perfect). You won't beat the best of them with a few Object.defineProperty hacks - they're playing a different game - but you can clear the low-hanging fruit.

The playwright-stealth library applies the standard patches:

BashCopy


shell
pip install playwright-stealth


plaintext

PythonCopy


python
from playwright_stealth import stealth_async

page = await context.new_page()
await stealth_async(page)


plaintext

This patches navigator.webdriver, chrome.runtime, permissions, plugin arrays, WebGL vendor, and a dozen other tells. It gets you past the basic checks. For the advanced checks (Cloudflare Turnstile, Datadome), you need residential proxies, real mouse movements, and realistic timings - or you use a service like browserless or Bright Data that handles this for you.

Behavioral stealth matters too. Anti-bot systems flag pages that load and immediately call page.evaluate. Add human-like delays:

PythonCopy


python
import random

await page.goto(url, wait_until="domcontentloaded")
await asyncio.sleep(random.uniform(1.5, 3.5)) # human-like pause
await page.mouse.move(random.randint(100, 800), random.randint(100, 600))
await asyncio.sleep(random.uniform(0.3, 0.8))

then scrape


markdown

It looks silly. It works. Anti-bot systems flag "0.1s page load → instant selector query" as bot behavior. Adding 2-5 seconds of randomized delay cuts detection dramatically, at the cost of throughput.

Distributed Workers with Redis

Single-machine scraping caps out around 50-100 requests/minute realistically. To go bigger, distribute across multiple workers coordinated via Redis.

PythonCopy


python

worker.py

import asyncio
import json
import hashlib
import os
import redis.asyncio as redis
from browser_pool import BrowserPool
from proxy_pool import ProxyPool

REDIS_URL = os.environ["REDIS_URL"]

async def process_url(pool: BrowserPool, proxy_pool: ProxyPool, r: redis.Redis, url: str) -> dict:
# Check if already done (dedup)
url_hash = hashlib.sha256(url.encode()).hexdigest()
if await r.hexists("scrape:done", url_hash):
return {"url": url, "status": "already_done"}

async with pool.acquire() as ctx:
page = await ctx.new_page()
try:
response = await page.goto(url, wait_until="domcontentloaded", timeout=30000)
if response is None or response.status >= 400:
await r.hincrby("scrape:failed", url, 1)
return {"url": url, "status": "failed", "code": response.status if response else None}

content = await page.content()
title = await page.title()

# Store result
result = {"url": url, "title": title, "html_length": len(content)}
await r.hset("scrape:done", url_hash, json.dumps(result))
await r.lpush("scrape:results", json.dumps(result))
return {"url": url, "status": "ok"}

finally:
await page.close()

async def worker_loop(worker_id: str):
r = redis.from_url(REDIS_URL, decode_responses=True)
pool = BrowserPool(size=4)
proxy_pool = ProxyPool(proxies=[os.environ["PROXY_ENDPOINT"]])
await pool.start()

print(f"Worker {worker_id} started")
try:
while True:
# BLPOP blocks until a URL is available, with 30s timeout
item = await r.blpop("scrape:pending", timeout=30)
if item is None:
continue # nothing to do, loop

_, url = item
try:
result = await process_url(pool, proxy_pool, r, url)
print(f"[{worker_id}] {result}")
except Exception as e:
await r.hincrby("scrape:failed", url, 1)
print(f"[{worker_id}] error on {url}: {e}")

finally:
await pool.stop()
await r.close()

if name == "main":
worker_id = os.environ.get("WORKER_ID", "w1")
asyncio.run(worker_loop(worker_id))


plaintext

URLs are pushed to scrape:pending by a producer (a script that reads a sitemap, a CSV, or an API). Workers BLPOP to claim a URL atomically - no double-scraping. Done URLs are tracked in scrape:done so crashed workers don't re-scrape on restart.

To seed URLs:

PythonCopy


python

seed.py

import asyncio
import redis.asyncio as redis

async def seed(urls: list[str]):
r = redis.from_url("redis://localhost:6379", decode_responses=True)
# Use RPUSH so URLs are FIFO; use LPUSH for LIFO
await r.rpush("scrape:pending", *urls)
await r.close()

asyncio.run(seed([f"https://example.test/p/{i}" for i in range(10000)]))


markdown

Run N workers across M machines, all pointing at the same Redis. Horizontal scaling with linear throughput, up to the limits of your proxy pool and the target's tolerance.

Retry Strategy: Don't Re-Do Successful Work

Real scraping fails constantly. A request times out, a proxy returns 502, the page takes 60s to render, the anti-bot system returns a CAPTCHA. Your retry strategy needs to handle this without re-scraping pages that already succeeded and without hammering failing pages.

PythonCopy


python
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type

class TransientError(Exception):
pass

@retry(
retry=retry_if_exception_type(TransientError),
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=2, min=2, max=30),
reraise=True,
)
async def scrape_with_retry(pool: BrowserPool, url: str) -> dict:
async with pool.acquire() as ctx:
page = await ctx.new_page()
try:
response = await page.goto(url, wait_until="domcontentloaded", timeout=20000)
if response is None:
raise TransientError(f"No response for {url}")
if response.status in {429, 502, 503, 504}:
raise TransientError(f"Transient status {response.status} for {url}")
if response.status >= 400:
# Permanent failure - don't retry
raise RuntimeError(f"Permanent failure {response.status} for {url}")
# ... scrape ...
return {"url": url, "ok": True}
finally:
await page.close()


markdown

The pattern: distinguish transient failures (retry) from permanent failures (give up). 429/502/503/504 are transient. 404/403/410 are permanent. Timeout is transient but only retry once or twice - a slow page is usually slow because of the target's anti-bot, and retrying will hit the same wall.

For the queue level: when a URL fails permanently, push it to a scrape:dead_letter list with the error message. A human reviews the dead letter queue daily and decides whether to fix the scraper (selector changed?) or skip the URL. Never silently drop failures - they're the signal that something needs attention.

Docker Packaging and Deployment

Playwright in production means Docker. The official image is large (1.5 GB) but pre-configured with browsers and system deps:

DockerfileCopy


docker

Dockerfile

FROM mcr.microsoft.com/playwright/python:v1.45.0-jammy

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

ENV PYTHONUNBUFFERED=1
ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright

CMD ["python", "-u", "worker.py"]


plaintext

YAMLCopy


yaml

docker-compose.yml

version: "3.9"
services:
redis:
image: redis:7-alpine
ports: ["6379:6379"]
volumes: ["redis-data:/data"]

worker:
build: .
environment:
REDIS_URL: "redis://redis:6379"
WORKER_ID: "w-${HOSTNAME}"
PROXY_ENDPOINT: "${PROXY_ENDPOINT}"
depends_on: [redis]
deploy:
replicas: 4
restart: unless-stopped

volumes:
redis-data:


markdown

deploy.replicas: 4 gives you 4 workers out of the box. Scale by changing the number or by running docker compose up --scale worker=12. Each worker runs its own browser pool - 4 workers × 4 contexts = 16 concurrent scrapes.

For Kubernetes, the pattern is a Deployment with N replicas pointing at a Redis StatefulSet. The browser image's --disable-dev-shm-usage flag is essential - Docker's default 64 MB /dev/shm is too small for Chromium and causes crashes. Alternative: shm_size: 2gb in compose.

Monitoring and Metrics

A scraper without metrics is a black box. You need to know: throughput (URLs/min), error rate, latency distribution, proxy health, queue depth.

PythonCopy


python

metrics.py

import time
from collections import defaultdict
from prometheus_client import Counter, Histogram, Gauge

URLS_PROCESSED = Counter(
"scraper_urls_processed_total", "URLs processed", ["status"]
)
URL_DURATION = Histogram(
"scraper_url_duration_seconds", "Time per URL",
buckets=[0.5, 1, 2, 5, 10, 20, 30, 60]
)
QUEUE_DEPTH = Gauge("scraper_queue_depth", "Pending URLs in queue")
PROXY_TIRED = Gauge("scraper_proxy_tired_total", "Proxies currently in cooldown")

In the worker loop:

start = time.time()
try:
result = await process_url(pool, proxy_pool, r, url)
URLS_PROCESSED.labels(status=result["status"]).inc()
except Exception as e:
URLS_PROCESSED.labels(status="error").inc()
finally:
URL_DURATION.observe(time.time() - start)

Expose /metrics via prometheus_client.start_http_server(9090). Alert on:

  • Error rate > 10% (something broke)
  • Queue depth growing (workers can't keep up - scale out)
  • Average latency > 30s (target is slowing you down - add proxies)
  • Proxy tired count > 50% (proxies exhausted - buy more)

A useful "is the scraper healthy?" check: log a heartbeat to healthchecks.io every minute. If the heartbeat stops, you get paged. This catches the worst failure mode - the worker process is "running" but stuck in a deadlock and not actually scraping.

Common Mistakes (and How to Spot Them)

Launching a browser per page. Symptom: throughput is 2 pages/minute and RAM grows unboundedly. Fix: use a browser pool with N reusable contexts.

Sleeping instead of waiting for selectors. Symptom: scraper is slow and flaky - sometimes the element is there, sometimes not. Fix: page.wait_for_selector(...) or page.wait_for_function(...).

No retry strategy. Symptom: a 502 from the target kills 20% of your scrape. Fix: tenacity with exponential backoff for transient failures.

Single IP, no rotation. Symptom: works for an hour, then 403s everywhere. Fix: proxy pool with cooldown, or a rotating proxy service.

Loading every resource. Symptom: 5 MB/page, 4s/page, $$$ in bandwidth. Fix: block images/fonts/analytics via page.route.

Not closing pages. Symptom: memory grows until OOM. Fix: await page.close() in a finally block; use async with where possible.

Re-scraping on crash. Symptom: worker restarts, scrapes 1000 URLs you already did. Fix: Redis dedup with hset of done URL hashes.

Ignoring robots.txt and ToS. Symptom: cease and desist from the target's lawyers. Fix: read both, respect them, or use official APIs where they exist.

Troubleshooting, From Real Production

"Browser closed unexpectedly". Chromium crashed, usually from OOM or /dev/shm too small. Fix: set shm_size: 2gb in Docker, or use --disable-dev-shm-usage. Also check the host's actual free RAM - Playwright is RAM-hungry.

"Navigation timeout". The page didn't reach wait_until state in time. Causes: target is slow, proxy is slow, the page never stops loading ads. Fix: lower the timeout, switch to wait_until="domcontentloaded", or block the resource that's hanging (often a tracking pixel that times out).

"Target closed" errors during evaluate. The page navigated or closed between your goto and your evaluate. Fix: re-fetch the page reference, or use page.wait_for_url if the navigation is expected.

"net::ERR_PROXY_CONNECTION_FAILED". The proxy is down or returning 407 auth required. Fix: check the proxy credentials, mark the proxy as tired, and retry with a different one.

"Detected as bot" / CAPTCHA page. The target's anti-bot flagged you. Fix: switch to residential proxies, slow down, add stealth patches, and add randomized mouse movements. If you're getting CAPTCHAs, you're past what basic evasion can fix - pay for a CAPTCHA-solving service or a managed scraper.

Workers idle, queue full. The BLPOP timeout is firing but workers aren't picking up work. Fix: check that the producer is using the right Redis list key, and that workers and producer share the same Redis database.

Cost Considerations

Component Cost at 100k URLs/day Notes
Workers (4× 2 vCPU) ~$120/mo Any cloud or self-hosted
Redis ~$15/mo Small instance is plenty
Residential proxies ~$300-1500/mo 100k URLs × ~2 MB = 200 GB; $1.5-7.5/GB
Storage (S3 for HTML) ~$25/mo 100k × 1 MB compressed = 100 GB
Outbound bandwidth ~$10-50/mo Cloud egress
Total ~$470-1700/mo Proxies dominate

The proxy cost dominates everything. Optimization levers:

  • Block images/fonts/analytics: cuts bandwidth 60-80%, directly cuts proxy cost.
  • Cache aggressively: many scrapes are re-scrapes of the same URL within a day. Cache results for 24h with a content hash.
  • Use datacenter proxies where possible: 5-10x cheaper, fine for non-aggressive targets.
  • Switch to API where available: many sites have official APIs that are cheaper, faster, and legal. Always check first.

For one-off or low-volume scraping (<10k URLs/day), browserless.cloud or ScrapingBee handle the infrastructure for $49-299/mo. Worth it if you don't want to operate workers.

Alternatives Comparison

Tool When Cost
httpx + BeautifulSoup Static HTML, no JS Free
Scrapy Static HTML at scale, with queueing/pipelines Free
Playwright (this article) JS-rendered pages, custom logic Free + infra
Puppeteer Same as Playwright, JS-only Free + infra
Selenium Legacy integration tests Free + infra
browserless.cloud Managed Playwright, no infra $50-500+/mo
ScrapingBee API-based, handles proxies/captchas $49-499/mo
Bright Data Enterprise scraping with built-in proxies $500+/mo
Apify Marketplace + actors for common sites Free tier, then $$

Decision: build with Playwright when you need custom logic at scale and can afford to operate infra. Use a managed service when you need 1-10k URLs and don't want to maintain workers. Use httpx/Scrapy when JS isn't needed.

Real-World Use Cases

  • Price monitoring: scrape 50k product pages daily across 5 competitor sites. Playwright for the SPA-heavy ones, httpx for the rest. Daily diff against yesterday's prices, alert on >5% changes.
  • Lead generation: scrape company directories (Crunchbase-style), enrich with data from each company's site, store in CRM. Playwright for the directory (JS-rendered), httpx for the enrichment.
  • Job board aggregation: scrape 200 job boards hourly, dedupe by job signature, expose via API. Playwright for the JS-heavy boards, Scrapy for the static ones.
  • SEO auditing: crawl a client's site, render each page in Playwright, extract meta tags, structured data, and Core Web Vitals. Weekly reports.
  • News monitoring: scrape 500 news sites hourly, extract article text, classify with LLM, alert on relevant topics. Playwright for the JS-rendered sites, RSS for the ones that publish feeds.

Conclusion

Playwright is the right tool when you need a real browser to extract data, and the patterns that scale are the ones nobody writes in the README: a browser pool instead of one browser per page, request interception to skip the junk, a Redis-backed queue with dedup so workers don't re-scrape, proxy rotation with cooldowns, retry strategies that distinguish transient from permanent failures, and stealth patches plus human-like delays to stay under the anti-bot radar. Build the single-page scraper first, then the pool, then the queue, then the distribution - each layer solves a problem you'll actually hit. Skip the layers and you'll spend your time firefighting; include them and your scraper will quietly do its job while you sleep.


Originally published on Mango Developer.

來源:DEV Community · dev.to