Abdelhafid Guesmia
All posts
Web Scraping at Scale Without Getting Blocked
ScrapyPlaywrightAnti-detectionPythonInfrastructure

Web Scraping at Scale Without Getting Blocked


Web Scraping at Scale Without Getting Blocked

Anyone can write a scraper that runs for an hour. The challenge is building one that runs for six months, 50k records a day, without breaking.

Here's what I've learned from running production scrapers.

Architecture First

Before writing a single spider, decide your architecture:

  • Scrapy for structured, high-volume scraping of HTML pages
  • Playwright for JavaScript-heavy sites that require browser rendering
  • Requests + BeautifulSoup for one-offs and prototypes only — it doesn't scale

For most production work, I use Scrapy as the orchestrator with Playwright for sites that need it, connected via scrapy-playwright.

Anti-Detection Measures

Rotate User Agents and Headers

# middlewares.py
import random

USER_AGENTS = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ...",
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605 ...",
    # add 10-20 real browser UAs
]

class RandomUserAgentMiddleware:
    def process_request(self, request, spider):
        request.headers["User-Agent"] = random.choice(USER_AGENTS)
        request.headers["Accept-Language"] = "en-US,en;q=0.9"
        request.headers["Accept-Encoding"] = "gzip, deflate, br"

Request Throttling

Hammering a site is the fastest way to get blocked. Use Scrapy's AutoThrottle:

# settings.py
AUTOTHROTTLE_ENABLED = True
AUTOTHROTTLE_START_DELAY = 1.0
AUTOTHROTTLE_MAX_DELAY = 10.0
AUTOTHROTTLE_TARGET_CONCURRENCY = 2.0
DOWNLOAD_DELAY = 0.5

Proxy Rotation

For sites with aggressive IP bans, rotating proxies are essential:

class ProxyMiddleware:
    def __init__(self, proxy_list):
        self.proxies = proxy_list

    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler.settings.getlist("PROXY_LIST"))

    def process_request(self, request, spider):
        request.meta["proxy"] = random.choice(self.proxies)

Handling JavaScript with Playwright

For sites that load data via JS, scrapy-playwright integrates cleanly:

class JSSitSpider(scrapy.Spider):
    name = "js_site"

    def start_requests(self):
        yield scrapy.Request(
            url="https://example.com/listings",
            meta={
                "playwright": True,
                "playwright_page_methods": [
                    PageMethod("wait_for_selector", "div.listing-card"),
                ],
            },
        )

    def parse(self, response):
        for card in response.css("div.listing-card"):
            yield {"title": card.css("h3::text").get(), ...}

Storing Data Reliably

Use a pipeline that writes to PostgreSQL with an upsert pattern — so re-runs don't create duplicates:

class PostgresPipeline:
    def process_item(self, item, spider):
        self.conn.execute("""
            INSERT INTO listings (id, title, price, scraped_at)
            VALUES (%(id)s, %(title)s, %(price)s, NOW())
            ON CONFLICT (id) DO UPDATE SET
                title = EXCLUDED.title,
                price = EXCLUDED.price,
                scraped_at = EXCLUDED.scraped_at
        """, dict(item))
        return item

Monitoring Long-Running Jobs

For a scraper running for months, you need alerting. I track:

  • Items scraped per hour (drop = something broke)
  • Error rate (spike = site changed or blocks started)
  • Database row count (should trend upward)

A simple Grafana dashboard over a job_metrics table is enough.

Summary

Production scraping checklist:

  1. Scrapy as the backbone, Playwright only where needed
  2. Rotate user agents, headers, and IPs
  3. AutoThrottle — never hammer a site
  4. Upsert to database — idempotent pipelines
  5. Monitor item rate and errors — know before it breaks

The scraper that runs for six months is the one that was built to be boring.