Web Scraping

How to Use Playwright for Web Scraping

Let me guess—you’ve been banging your head against the wall trying to scrape a modern website, only to find that BeautifulSoup gives you nothing but empty divs and loading spinners. Been there. The problem isn’t you—it’s that websites today don’t work like they did five years ago.

Here’s the truth: about 70% of websites you’ll want to scrape now rely heavily on JavaScript to load their content. They use React, Vue, Angular, and other frameworks that render everything client-side. Your traditional HTTP request grabs the initial HTML, but the actual data? That loads seconds later through AJAX calls you never see. This is where Playwright becomes your best friend.

I’ve been scraping websites for years, and Playwright has genuinely changed the game. Unlike older tools that feel clunky and outdated, Playwright gives you a real browser that sees websites exactly how users see them. You can click buttons, scroll pages, wait for content to load, and extract data after JavaScript finishes its magic. What’s more, it works across Chrome, Firefox, and Safari with the same code.

In this guide, you’re getting everything I wish someone had told me when I started. We’ll go from zero to building production-ready scrapers that handle authentication, bypass basic anti-bot systems, and scrape thousands of pages efficiently. No fluff—just practical techniques that work in the real world. Whether you’re monitoring competitor prices, building datasets for machine learning, or automating repetitive research tasks, you’ll have the tools you need by the end of this article.

Table of Contents

What Exactly Is Playwright and Why Does It Matter for Web Scraping?

Playwright is Microsoft’s open-source browser automation framework that lets you control Chrome, Firefox, and Safari through code. Think of it as your personal robot that opens browsers, navigates websites, interacts with pages, and extracts data—all while you sit back and watch (or more likely, run it headless in the background).

Microsoft’s team built Playwright after creating Puppeteer at Google. They learned from years of experience and designed something better. The result? A tool that’s faster, more reliable, and supports multiple browsers out of the box. That last part matters more than you might think—some websites behave differently across browsers, and being able to test that quickly saves hours of frustration.

Why Traditional Scrapers Fail Where Playwright Succeeds

Let’s talk about why your old scraping methods keep failing. When you use something like requests and BeautifulSoup in Python, here’s what happens:

  1. You send an HTTP GET request to the server
  2. The server sends back HTML
  3. You parse that HTML looking for data
  4. You find nothing because the data isn’t there yet

Modern websites work differently. The initial HTML is basically a skeleton. JavaScript runs in the browser, makes additional requests to APIs, and dynamically builds the page you see. By the time you’re looking at product listings or search results, dozens of AJAX calls have happened that your simple HTTP client never witnessed.

Playwright solves this by literally opening a real browser. Here’s what happens instead:

  1. Playwright launches Chrome (or Firefox/Safari)
  2. The browser loads the URL
  3. JavaScript executes naturally
  4. AJAX requests fire and complete
  5. Content renders on the page
  6. Now you extract the data that’s actually there

From an implementation perspective, this means you’re working with the fully-rendered DOM instead of the initial HTML. Everything that a human user would see, you can now access programmatically.

Core Features That Make Playwright a Scraping Powerhouse

Auto-Waiting That Just Works: Honestly, this feature alone is worth switching to Playwright. The framework automatically waits for elements to be visible, enabled, and ready before interacting with them. No more littering your code with time.sleep(3) and hoping that’s long enough. Playwright figures it out.

Cross-Browser Consistency: Write your scraper once, run it on Chromium, Firefox, or WebKit. The API stays identical. In testing, I’ve found that about 15% of websites render differently across browsers, and having this flexibility built-in saves countless debugging hours.

Network Interception: You can intercept HTTP requests, modify headers, block resources (like images or ads), and even read AJAX responses directly. This capability opens up advanced techniques we’ll explore later. Learn about handling anti-bot protection effectively.

Multi-Language Support: Whether you’re comfortable with Python, JavaScript, Java, or C#, Playwright speaks your language. The examples in this guide use Python because it’s beginner-friendly, but everything translates easily.

Built-In Screenshot and PDF Generation: Sometimes you need visual proof of what a page looked like. Playwright captures full-page screenshots and generates PDFs with a single method call.

How Playwright Actually Works Behind the Scenes

Understanding what’s happening under the hood helps you write better scrapers and debug issues faster. When you run a Playwright script, here’s the system architecture at play:

Playwright communicates with browsers through the DevTools Protocol (CDP for Chromium-based browsers) or similar protocols for Firefox and WebKit. This is the same protocol developer tools use when you inspect websites in your browser. The system relies on a client-server model where your Python code acts as the client, sending commands like “click this button” or “extract this text” to the browser server.

Here’s the complete workflow:

  1. Initialization: Playwright starts a browser process with specific configurations
  2. Context Creation: Browser contexts (think incognito windows) provide isolation
  3. Page Management: New pages (tabs) open within contexts
  4. Navigation: Pages load URLs and wait for content
  5. Interaction: Your script interacts with elements—clicking, typing, scrolling
  6. Extraction: You grab data from the fully-rendered DOM
  7. Cleanup: Browsers and contexts close, freeing system resources

The key component here is that everything happens in a real browser environment. JavaScript executes, cookies persist, local storage works—your automation is nearly indistinguishable from a human user (at least visually).

Getting Your Hands Dirty: Installing Playwright Step by Step

Let’s get Playwright running on your machine. We’ll cover both Python and JavaScript installations since they’re the most popular choices among web scrapers.

Setting Up Playwright with Python

Before anything else, you’ll need Python 3.8 or higher installed. Check your version by opening a terminal and running:

Bash
python --version

If you’re on an older version or don’t have Python at all, grab the latest from python.org. Once that’s sorted, create a new directory for your scraping project:

Bash
mkdir playwright-scraper
cd playwright-scraper

Now install Playwright using pip:

Bash
pip install playwright

This downloads the Playwright package, but here’s something that trips up beginners: Playwright doesn’t use the browsers already on your computer. It needs its own optimized browser binaries. Download them with:

Bash
playwright install

You’ll see it downloading Chromium, Firefox, and WebKit. Each browser is around 200-300MB, so this takes a few minutes. Grab a coffee—you’ve earned it.

Once everything’s installed, let’s verify it works. Create a file called test.py and add this code:

PYTHON
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    page = browser.new_page()
    page.goto('https://example.com')
    print(f'Page title: {page.title()}')
    browser.close()

Run it with python test.py. You should see a Chrome window pop up, load the page, and then close. If you see the page title printed in your terminal, congratulations—you’re ready to scrape.

Setting Up Playwright with Node.js and JavaScript

JavaScript developers, this one’s for you. Make sure Node.js 16 or higher is installed:

Bash
node --version

Create your project directory and initialize it:

Bash
mkdir playwright-scraper
cd playwright-scraper
npm init -y

Install Playwright:

Bash
npm install playwright

Download the browser binaries:

Bash
npx playwright install

Here’s your first JavaScript scraper to test the setup:

JAVASCRIPT
const { chromium } = require('playwright');

(async () => {
    const browser = await chromium.launch({ headless: false });
    const page = await browser.newPage();
    await page.goto('https://example.com');
    console.log(`Page title: ${await page.title()}`);
    await browser.close();
})();

Save this as test.js and run node test.js. You should see the same behavior—a browser opens, loads the page, and closes after printing the title.

Common Installation Hiccups and How to Fix Them

“playwright: command not found”: This usually means the installation didn’t complete properly. Try uninstalling and reinstalling: pip uninstall playwright then pip install playwright.

Browser download fails: Some corporate networks block the download. You can manually download browsers or use the PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD environment variable and install them separately.

Permission errors on Linux: You might need additional system dependencies. Run: playwright install-deps to install them automatically.

Your First Real Scraper: Extracting Product Data from a Dynamic E-commerce Site

Theory’s great, but let’s build something real. We’re going to scrape product information from a website that loads everything dynamically. This mirrors what you’ll encounter in production environments.

Step 1: Understanding Your Target Before Writing Code

Before touching your keyboard, you need to understand what you’re scraping. Open your target website in a regular browser (I recommend using Chrome’s incognito mode). Right-click on a product and select “Inspect” to open DevTools.

Look at the HTML structure. You’ll want to identify:

  • Container elements that hold multiple products
  • CSS classes or IDs that consistently mark product cards
  • Where product names, prices, and images live in the DOM
  • Whether content loads immediately or after a delay

Here’s a pro tip: check if the site uses data-testid or similar attributes. Developers add these for testing purposes, and they rarely change. They make your selectors more stable than CSS classes that might get updated during redesigns.

Next, open the Network tab in DevTools and reload the page. Watch for XHR or Fetch requests. If you see API calls fetching JSON data, that’s dynamic content loading. This confirms you need Playwright instead of a simple HTTP scraper.

Step 2: Building the Basic Scraper Structure

Let’s start with a complete working example that scrapes product data:

PYTHON
from playwright.sync_api import sync_playwright
import json
import time

def scrape_products(url):
    """
    Scrapes product information from an e-commerce site
    """
    with sync_playwright() as p:
        # Launch browser in headless mode for production
        # Set headless=False while developing to watch what happens
        browser = p.chromium.launch(headless=True)

        # Create a new page
        page = browser.new_page()

        print(f'Navigating to {url}...')
        page.goto(url, wait_until='networkidle')

        # Wait for products to actually load
        # This selector should match your target site's structure
        print('Waiting for products to load...')
        page.wait_for_selector('.product-card', timeout=30000)

        # Give JavaScript a moment to finish rendering
        time.sleep(2)

        # Extract product data
        print('Extracting product information...')
        products = []

        # Find all product containers
        product_elements = page.query_selector_all('.product-card')

        for element in product_elements:
            try:
                # Extract individual fields
                name_elem = element.query_selector('.product-name')
                price_elem = element.query_selector('.product-price')
                image_elem = element.query_selector('img')
                link_elem = element.query_selector('a')

                # Build product object
                product = {
                    'name': name_elem.inner_text() if name_elem else 'N/A',
                    'price': price_elem.inner_text() if price_elem else 'N/A',
                    'image': image_elem.get_attribute('src') if image_elem else 'N/A',
                    'url': link_elem.get_attribute('href') if link_elem else 'N/A'
                }

                products.append(product)

            except Exception as e:
                print(f'Error extracting product: {e}')
                continue

        print(f'Successfully scraped {len(products)} products')

        # Save to JSON file
        with open('products.json', 'w', encoding='utf-8') as f:
            json.dump(products, indent=2, ensure_ascii=False, fp=f)

        browser.close()
        return products

if __name__ == '__main__':
    # Replace with your target URL
    target_url = 'https://example-store.com/products'
    products = scrape_products(target_url)

    # Print first few products
    for product in products[:3]:
        print(f"\nProduct: {product['name']}")
        print(f"Price: {product['price']}")
        print(f"URL: {product['url']}")

Step 3: Breaking Down What Just Happened

Let’s walk through the critical parts of this code:

The wait_until='networkidle' parameter tells Playwright to wait until no new network connections are made for 500ms. This is brilliant for sites that load content via AJAX—it ensures everything’s finished loading before you try to extract data.

The wait_for_selector() method is your safety net. It pauses execution until the specified element appears in the DOM. Without this, you’d try to extract products before they exist, causing your scraper to fail.

The query_selector_all() method returns a list of all elements matching your selector. We iterate through this list to extract data from each product. Worth noting is that this returns an empty list if nothing matches—it won’t throw an error.

Error handling inside the loop is crucial. If one product has missing fields or a different structure, we catch the exception and continue with the next product instead of crashing the entire script.

Step 4: Customizing Selectors for Your Target Site

You’ll need to adjust the selectors (.product-card, .product-name, etc.) to match your actual target website. Here’s how to find the right selectors:

  1. Right-click on a product element and select “Inspect”
  2. Look for unique, stable identifiers in this order:
    • data-testid attributes (most stable)
    • id attributes (stable but might not exist)
    • Specific class names that describe function, not style
    • Element structure with child selectors

Here are some example selectors for common scenarios:

PYTHON
# Using data attributes (most reliable)
products = page.query_selector_all('[data-testid="product-item"]')

# Using multiple classes
products = page.query_selector_all('.product.card.item')

# Using parent-child relationships
products = page.query_selector_all('div.products-grid > div.product')

# Combining attributes
products = page.query_selector_all('div[data-component="ProductCard"]')

In real-world situations, you’ll often need to experiment with different selectors. Run your scraper with headless=False so you can see what’s happening and adjust selectors based on what actually appears on the page.


Mastering Element Selection: The Foundation of Reliable Scrapers

Getting element selection right makes the difference between scrapers that work for months and ones that break every week. Let’s dive deep into selection strategies.

CSS Selectors vs XPath: What Should You Actually Use?

CSS selectors are your go-to choice 95% of the time. They’re faster, more readable, and everyone who’s done basic web development already understands them. Here are the patterns you’ll use most:

PYTHON
# Select by class
page.query_selector('.product-name')

# Select by ID
page.query_selector('#main-content')

# Select by attribute
page.query_selector('[data-testid="price"]')

# Select by multiple classes
page.query_selector('.product.featured.new')

# Child combinator
page.query_selector('div.container > h1.title')

# Descendant combinator
page.query_selector('div.container h1.title')

# Attribute contains
page.query_selector('[class*="product"]')

# Multiple selectors
page.query_selector('h1, h2, h3')

XPath becomes useful when CSS isn’t enough. Specifically, when you need to:

  • Select elements by their text content
  • Navigate to parent elements
  • Use complex conditional logic
PYTHON
# Select by text content
page.query_selector('//button[contains(text(), "Add to Cart")]')

# Select parent element
page.query_selector('//span[@class="price"]/..')

# Select following sibling
page.query_selector('//h3[@class="title"]/following-sibling::div')

# Complex conditions
page.query_selector('//div[@class="product" and @data-available="true"]')

From my experience, stick with CSS selectors until you hit a wall. Then reach for XPath. Mixing both keeps your code readable while handling edge cases.

Building Selectors That Survive Website Updates

Here’s a painful truth: websites change. That beautiful selector you crafted breaks six months later when the marketing team redesigns the product page. Let’s build selectors that last.

Priority order for selector stability:

  1. Data attributes (data-testid, data-cy): These are added for testing and rarely change
  2. ARIA labels (aria-label, role): Accessibility attributes stay consistent
  3. IDs: Usually stable but might not exist on all elements
  4. Semantic HTML (article, <nav>, <section>): Structure tends to be stable
  5. Class names that describe function (product-card, price-display): Better than style-based classes
  6. Class names that describe style (bg-blue, flex-row): These change frequently

Here’s the same selector written with different stability levels:

PYTHON
# Most stable: data attribute
element = page.query_selector('[data-testid="product-price"]')

# Very stable: ARIA label
element = page.query_selector('[aria-label="Product price"]')

# Stable: ID
element = page.query_selector('#product-price')

# Moderate stability: functional class
element = page.query_selector('.product-price')

# Low stability: style-based class (avoid!)
element = page.query_selector('.text-lg.font-bold.text-green-600')

In practice, inspect the target website’s HTML and look for patterns. Sites built with modern testing practices often include data-testid attributes everywhere. Use them religiously.

Handling Dynamic IDs and Classes

Some websites generate random IDs like element-abc123 that change on every page load. Frustrating, but solvable:

PYTHON
# Partial attribute matching
page.query_selector('[id^="product-"]')  # Starts with "product-"
page.query_selector('[id$="-price"]')    # Ends with "-price"
page.query_selector('[id*="product"]')   # Contains "product"

# Use parent-child relationships
page.query_selector('div.product-container > div[id^="item-"]')

# Combine multiple stable attributes
page.query_selector('div[data-type="product"][class*="card"]')

Another trick is selecting by element position when structure is stable:

PYTHON
# Select the third product
products = page.query_selector_all('.product')
third_product = products[2] if len(products) > 2 else None

# First child
first_item = page.query_selector('.product-list > *:first-child')

# Last child
last_item = page.query_selector('.product-list > *:last-child')

Taming Dynamic Content: Waiting Strategies That Actually Work

Modern websites don’t load everything at once. They trickle in content as users scroll, click buttons, or simply wait. Mastering waiting strategies separates amateur scrapers from professional ones.

Understanding Playwright’s Auto-Waiting Mechanism

Here’s something that’ll save you countless hours: Playwright automatically waits for elements to be “actionable” before interacting with them. When you call page.click('.button'), Playwright:

  1. Waits for the element to exist in the DOM
  2. Waits for it to become visible
  3. Waits for it to stop moving (animations complete)
  4. Waits for it to be enabled (not disabled)
  5. Scrolls it into view if needed
  6. Then clicks it

This happens automatically with a default timeout of 30 seconds. In most cases, you don’t need to add any explicit waits. Just write your interaction code and let Playwright handle the timing.

Explicit Wait Strategies for Complex Scenarios

Sometimes auto-waiting isn’t enough. Maybe content loads through multiple stages, or you need to wait for specific conditions. Here are the patterns I use most:

Wait for an element to appear:

PYTHON
# Basic wait for element
page.wait_for_selector('.product-loaded', state='visible', timeout=30000)

# Wait for multiple possible selectors
page.wait_for_selector('.product-loaded, .content-ready', timeout=30000)

# Wait for element with specific text
page.wait_for_selector('text=Products loaded successfully')

Wait for an element to disappear:

PYTHON
# Wait for loading spinner to vanish
page.wait_for_selector('.loading-spinner', state='hidden', timeout=60000)

# Wait for overlay to detach from DOM
page.wait_for_selector('.modal-overlay', state='detached')

Wait for network activity to settle:

PYTHON
# Wait until no network connections for 500ms
page.goto('https://example.com', wait_until='networkidle')

# Alternative: wait for specific load state
page.goto('https://example.com', wait_until='domcontentloaded')

Wait for custom JavaScript conditions:

PYTHON
# Wait until a global variable is set
page.wait_for_function('window.dataLoaded === true')

# Wait until specific element count
page.wait_for_function('document.querySelectorAll(".product").length >= 20')

# Wait for jQuery to finish (if site uses it)
page.wait_for_function('jQuery.active === 0')

Intercepting AJAX Responses for Faster Scraping

Here’s a technique that’ll blow your mind: instead of waiting for content to render on the page, intercept the AJAX responses and extract data directly from the JSON. This is often 3-5x faster than waiting for DOM updates.

PYTHON
def scrape_via_api_interception():
    """
    Intercepts API calls and extracts data from responses
    """
    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page()

        # Store intercepted data
        api_responses = []

        def handle_response(response):
            # Check if this is the API endpoint we care about
            if '/api/products' in response.url and response.status == 200:
                try:
                    # Extract JSON data
                    data = response.json()
                    api_responses.append(data)
                    print(f'Intercepted API response with {len(data)} items')
                except:
                    pass  # Not JSON or parse error

        # Register the response handler
        page.on('response', handle_response)

        # Navigate to the page (triggers API calls)
        page.goto('https://example.com/products')

        # Wait a moment for all requests to complete
        page.wait_for_timeout(3000)

        browser.close()

        # Process the intercepted data
        all_products = []
        for response_data in api_responses:
            if isinstance(response_data, list):
                all_products.extend(response_data)
            elif isinstance(response_data, dict) and 'products' in response_data:
                all_products.extend(response_data['products'])

        return all_products

# Use it
products = scrape_via_api_interception()
print(f'Got {len(products)} products directly from API')

This approach bypasses the entire rendering pipeline. You get raw JSON data directly from the server—exactly what the website received before it built the UI. Understanding how APIs work for scraping helps you identify these opportunities.

Handling Infinite Scroll and Lazy Loading

Many modern sites implement infinite scroll—more content loads as you scroll down. Here’s how to scrape them all:

PYTHON
def scrape_infinite_scroll(url, scroll_pause_time=2):
    """
    Scrapes sites with infinite scroll by repeatedly scrolling
    """
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        page = browser.new_page()
        page.goto(url)

        # Wait for initial content
        page.wait_for_selector('.item')

        last_height = page.evaluate('document.body.scrollHeight')
        items_found = 0

        while True:
            # Scroll to bottom
            page.evaluate('window.scrollTo(0, document.body.scrollHeight)')

            # Wait for new content to load
            page.wait_for_timeout(scroll_pause_time * 1000)

            # Calculate new scroll height
            new_height = page.evaluate('document.body.scrollHeight')

            # Count items
            current_items = page.query_selector_all('.item')
            current_count = len(current_items)

            print(f'Found {current_count} items so far...')

            # Check if we've reached the bottom
            if new_height == last_height and current_count == items_found:
                print('Reached the bottom of the page')
                break

            last_height = new_height
            items_found = current_count

        # Now extract all loaded items
        all_items = page.query_selector_all('.item')
        results = []

        for item in all_items:
            # Extract data from each item
            data = extract_item_data(item)
            results.append(data)

        browser.close()
        return results

In practice, you’ll want to add safeguards against infinite loops. Set a maximum number of scrolls or a maximum number of items to prevent runaway scraping if something goes wrong.


Becoming Invisible: Anti-Detection Techniques That Work in 2026

Let’s address the elephant in the room: websites don’t want to be scraped by bots. They employ increasingly sophisticated detection methods. Here’s how to fly under the radar.

Why Websites Detect Playwright (And What Gives You Away)

Out of the box, Playwright leaves several telltale signs that scream “I’m a bot!”:

The navigator.webdriver property: In automated browsers, navigator.webdriver returns true. Real browsers return undefined. Websites check this instantly.

Missing or incorrect properties: Automated browsers have different values for window.chrome, navigator.plugins, navigator.languages, and dozens of other properties.

Behavioral patterns: Real humans don’t navigate at constant speeds, never move their mouse, or click buttons 0.001 seconds after page load. Bots do this all the time.

Browser fingerprinting: Advanced systems create unique fingerprints based on canvas rendering, WebGL parameters, audio context, and font rendering. Automated browsers produce different fingerprints than real ones.

The good news? We can address most of these.

Step 1: Customize User-Agent and Headers

The default User-Agent screams automation. Change it to something realistic:

PYTHON
def create_stealth_browser():
    """
    Creates a browser with stealthy configuration
    """
    with sync_playwright() as p:
        # Launch browser
        browser = p.chromium.launch(
            headless=True,
            args=[
                '--disable-blink-features=AutomationControlled',
                '--disable-dev-shm-usage',
                '--no-sandbox'
            ]
        )

        # Create context with custom user agent
        context = browser.new_context(
            user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
            viewport={'width': 1920, 'height': 1080},
            locale='en-US',
            timezone_id='America/New_York'
        )

        # Create page
        page = context.new_page()

        return browser, page

browser, page = create_stealth_browser()
page.goto('https://bot-protected-site.com')

Better yet, rotate User-Agents randomly to avoid patterns:

PYTHON
import random

USER_AGENTS = [
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
    'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0'
]

context = browser.new_context(
    user_agent=random.choice(USER_AGENTS)
)

Step 2: Install Playwright Stealth Plugin

The playwright-stealth plugin patches dozens of browser properties automatically. It’s a game-changer:

Bash
pip install playwright-stealth
PYTHON
from playwright.sync_api import sync_playwright
from playwright_stealth import stealth_sync

def scrape_with_stealth(url):
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        page = browser.new_page()

        # Apply stealth mode
        stealth_sync(page)

        # Now navigate
        page.goto(url)

        # The page thinks you're a real browser!
        data = extract_data(page)

        browser.close()
        return data

This plugin modifies properties like:

  • navigator.webdriver (sets to undefined)
  • navigator.plugins (adds realistic plugins)
  • Canvas fingerprinting (randomizes output)
  • WebGL parameters (matches real browsers)
  • Chrome runtime properties

In my testing, this alone bypasses about 60% of basic bot detection systems.

Step 3: Simulate Human-Like Behavior

Real users don’t behave like robots. Add randomness and delays to mimic human behavior:

PYTHON
import random
import time

def human_like_delay(min_seconds=1, max_seconds=3):
    """Random delay between actions"""
    time.sleep(random.uniform(min_seconds, max_seconds))

def move_mouse_naturally(page, element):
    """Move mouse to element before clicking"""
    box = element.bounding_box()
    if box:
        # Move to element center with small random offset
        x = box['x'] + box['width'] / 2 + random.randint(-10, 10)
        y = box['y'] + box['height'] / 2 + random.randint(-10, 10)
        page.mouse.move(x, y)
        human_like_delay(0.2, 0.5)

def type_like_human(page, selector, text):
    """Type text with random delays between keystrokes"""
    element = page.query_selector(selector)
    element.click()

    for char in text:
        element.type(char, delay=random.randint(50, 150))

def scroll_like_human(page, scrolls=5):
    """Scroll page in chunks with random delays"""
    for _ in range(scrolls):
        # Random scroll distance
        scroll_amount = random.randint(300, 700)
        page.evaluate(f'window.scrollBy(0, {scroll_amount})')

        # Random pause
        human_like_delay(0.5, 2)

# Example usage
def scrape_with_human_behavior(url):
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        page = browser.new_page()

        page.goto(url)
        human_like_delay(2, 4)  # Initial pause

        # Scroll around like a human browsing
        scroll_like_human(page, scrolls=3)

        # Click a button naturally
        button = page.query_selector('.load-more')
        if button:
            move_mouse_naturally(page, button)
            button.click()
            human_like_delay(1, 3)

        # Extract data
        data = extract_data(page)

        browser.close()
        return data

These patterns make your automation much harder to distinguish from real user behavior. Learn more about web scraping best practices that keep your scrapers undetected.

Step 4: Rotate IPs with Proxies

Even with perfect browser fingerprints, scraping thousands of pages from the same IP address raises red flags. Proxies distribute your requests across multiple IPs. We’ll cover proxy configuration in depth in the next section.


Configuring Proxies: Your Shield Against IP Bans

If you’re serious about scraping at scale, proxies aren’t optional—they’re essential. Let’s set them up properly.

Understanding Proxy Types for Web Scraping

Not all proxies are created equal. Here’s what you need to know:

Datacenter Proxies: Fast and cheap, but websites easily detect them. They come from cloud providers like AWS or DigitalOcean, not real users’ devices. Good for scraping sites without heavy bot protection. Cost: $1-3 per GB.

Residential Proxies: IPs from real residential internet connections. Much harder to detect and block. Essential for scraping protected sites. Cost: $5-15 per GB. Compare residential vs datacenter proxies to choose the right option.

Mobile Proxies: IPs from mobile carriers (4G/5G). Most expensive but highest success rates on heavily protected sites. Cost: $20-50 per GB. Understand mobile proxy benefits.

ISP Proxies: Hybrid between datacenter and residential. Fast like datacenter but registered to ISPs like residential. Good balance of speed and detection avoidance. Learn about ISP proxies.

For most scraping projects, residential proxies offer the best balance of cost and effectiveness.

Setting Up Basic Proxy Configuration in Playwright

Playwright makes proxy configuration straightforward. You can set proxies at the browser or context level:

PYTHON
def create_browser_with_proxy(proxy_server, username=None, password=None):
    """
    Creates a Playwright browser with proxy configuration
    """
    with sync_playwright() as p:
        # Proxy configuration
        proxy_config = {
            'server': proxy_server  # Format: 'http://ip:port' or 'https://ip:port'
        }

        # Add authentication if provided
        if username and password:
            proxy_config['username'] = username
            proxy_config['password'] = password

        # Launch browser with proxy
        browser = p.chromium.launch(
            headless=True,
            proxy=proxy_config
        )

        return browser

# Example usage
browser = create_browser_with_proxy(
    proxy_server='http://proxy-provider.com:8080',
    username='your_username',
    password='your_password'
)

page = browser.new_page()
page.goto('https://api.ipify.org')  # Check your IP
print(page.content())  # Should show proxy IP, not your real IP
browser.close()

Implementing Rotating Proxies for Large-Scale Scraping

For scraping thousands of URLs, you need to rotate proxies to avoid rate limits. Here’s a production-ready implementation:

PYTHON
import random
from playwright.sync_api import sync_playwright

class ProxyRotator:
    def __init__(self, proxy_list):
        """
        Initialize with list of proxy configurations
        proxy_list format: [
            {'server': 'http://ip1:port', 'username': 'user1', 'password': 'pass1'},
            {'server': 'http://ip2:port', 'username': 'user2', 'password': 'pass2'},
        ]
        """
        self.proxies = proxy_list
        self.current_index = 0

    def get_next_proxy(self):
        """Get next proxy in rotation"""
        proxy = self.proxies[self.current_index]
        self.current_index = (self.current_index + 1) % len(self.proxies)
        return proxy

    def get_random_proxy(self):
        """Get random proxy from pool"""
        return random.choice(self.proxies)

def scrape_urls_with_rotating_proxies(urls, proxies):
    """
    Scrape multiple URLs using rotating proxies
    """
    rotator = ProxyRotator(proxies)
    results = []

    for i, url in enumerate(urls):
        # Get next proxy in rotation
        proxy = rotator.get_next_proxy()

        print(f'Scraping {url} with proxy {proxy["server"]}')

        with sync_playwright() as p:
            try:
                browser = p.chromium.launch(
                    headless=True,
                    proxy=proxy
                )

                page = browser.new_page()
                page.goto(url, timeout=30000)

                # Extract data
                data = {
                    'url': url,
                    'title': page.title(),
                    'proxy_used': proxy['server']
                }

                results.append(data)

                browser.close()

            except Exception as e:
                print(f'Error scraping {url}: {e}')
                results.append({'url': url, 'error': str(e)})

        # Polite delay between requests
        time.sleep(random.uniform(2, 5))

    return results

# Example usage
proxy_list = [
    {'server': 'http://proxy1.com:8080', 'username': 'user1', 'password': 'pass1'},
    {'server': 'http://proxy2.com:8080', 'username': 'user2', 'password': 'pass2'},
    {'server': 'http://proxy3.com:8080', 'username': 'user3', 'password': 'pass3'},
]

urls_to_scrape = [
    'https://example.com/page1',
    'https://example.com/page2',
    'https://example.com/page3',
]

results = scrape_urls_with_rotating_proxies(urls_to_scrape, proxy_list)

This ensures no single proxy gets overused, reducing the chance of IP bans. Find the best rotating proxy providers for your needs.

Testing Proxy Performance

Not all proxies perform equally. Test them before committing to large-scale scraping:

PYTHON
def test_proxy_performance(proxy_config):
    """
    Tests proxy speed and reliability
    """
    import time

    with sync_playwright() as p:
        try:
            start_time = time.time()

            browser = p.chromium.launch(
                headless=True,
                proxy=proxy_config
            )

            page = browser.new_page()
            page.goto('https://api.ipify.org', timeout=10000)

            ip_address = page.inner_text('body')
            load_time = time.time() - start_time

            browser.close()

            return {
                'proxy': proxy_config['server'],
                'ip': ip_address,
                'load_time': round(load_time, 2),
                'status': 'working'
            }

        except Exception as e:
            return {
                'proxy': proxy_config['server'],
                'error': str(e),
                'status': 'failed'
            }

# Test all your proxies
for proxy in proxy_list:
    result = test_proxy_performance(proxy)
    print(f"Proxy: {result['proxy']}")
    if result['status'] == 'working':
        print(f"  IP: {result['ip']}, Load time: {result['load_time']}s")
    else:
        print(f"  Error: {result['error']}")

Handling CAPTCHAs: When Websites Fight Back

CAPTCHAs exist specifically to stop automated scraping. Let’s talk about handling them legally and effectively.

Types of CAPTCHAs You’ll Encounter

reCAPTCHA v2: The classic “I’m not a robot” checkbox, sometimes followed by image challenges (“Select all traffic lights”). Understanding reCAPTCHA helps you recognize it.

reCAPTCHA v3: Invisible scoring system that analyzes user behavior. No visible checkbox—it runs silently in the background and assigns a score. Low scores trigger challenges.

hCaptcha: Similar to reCAPTCHA but privacy-focused. Growing in popularity. Compare hCaptcha vs reCAPTCHA.

Cloudflare Turnstile: Newer alternative that’s faster and less annoying for users. Learn about Cloudflare Turnstile.

FunCAPTCHA: Interactive challenges like rotating objects or drag-and-drop puzzles.

Bypassing CAPTCHAs with Playwright Stealth

Sometimes, good stealth configuration alone prevents CAPTCHAs from appearing:

PYTHON
from playwright.sync_api import sync_playwright
from playwright_stealth import stealth_sync

def scrape_without_triggering_captcha(url):
    with sync_playwright() as p:
        # Use undetected Chrome
        browser = p.chromium.launch(
            headless=False,  # Some CAPTCHAs trigger more in headless
            args=[
                '--disable-blink-features=AutomationControlled',
                '--disable-dev-shm-usage'
            ]
        )

        context = browser.new_context(
            user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
            viewport={'width': 1920, 'height': 1080}
        )

        page = context.new_page()
        stealth_sync(page)

        # Navigate slowly like a human
        page.goto(url)
        page.wait_for_timeout(3000)

        # Check if CAPTCHA appeared
        captcha_present = page.query_selector('iframe[src*="recaptcha"]') is not None

        if not captcha_present:
            print('No CAPTCHA triggered!')
            data = extract_data(page)
            browser.close()
            return data
        else:
            print('CAPTCHA appeared, need solving service')
            browser.close()
            return None

Bypass CAPTCHA verification strategies provide more techniques.

Using CAPTCHA Solving Services

When stealth isn’t enough, CAPTCHA solving services employ human workers or AI to solve challenges for you:

PYTHON
import requests
import time

class CaptchaSolver:
    def __init__(self, api_key, service_url):
        self.api_key = api_key
        self.service_url = service_url

    def solve_recaptcha(self, site_key, page_url):
        """
        Solves reCAPTCHA v2 using external service
        """
        # Submit CAPTCHA task
        task_payload = {
            'clientKey': self.api_key,
            'task': {
                'type': 'RecaptchaV2TaskProxyless',
                'websiteURL': page_url,
                'websiteKey': site_key
            }
        }

        response = requests.post(
            f'{self.service_url}/createTask',
            json=task_payload
        )
        task_id = response.json()['taskId']

        # Poll for solution
        while True:
            result = requests.post(
                f'{self.service_url}/getTaskResult',
                json={'clientKey': self.api_key, 'taskId': task_id}
            )

            status = result.json()['status']

            if status == 'ready':
                return result.json()['solution']['gRecaptchaResponse']
            elif status == 'processing':
                time.sleep(5)
            else:
                raise Exception(f'CAPTCHA solving failed: {status}')

def scrape_with_captcha_solving(url):
    """
    Complete scraping flow with CAPTCHA solving
    """
    solver = CaptchaSolver(
        api_key='your_api_key',
        service_url='https://api.anti-captcha.com'
    )

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        page = browser.new_page()

        page.goto(url)

        # Check if CAPTCHA appeared
        captcha_iframe = page.query_selector('iframe[src*="recaptcha"]')

        if captcha_iframe:
            print('CAPTCHA detected, solving...')

            # Extract site key
            site_key = page.get_attribute('[data-sitekey]', 'data-sitekey')

            # Solve CAPTCHA
            solution = solver.solve_recaptcha(site_key, url)

            # Inject solution
            page.evaluate(f'''
                document.getElementById("g-recaptcha-response").innerHTML = "{solution}";
                if (typeof ___grecaptcha_cfg !== 'undefined') {{
                    Object.keys(___grecaptcha_cfg.clients).forEach(function(key) {{
                        ___grecaptcha_cfg.clients[key].callback(solution);
                    }});
                }}
            ''')

            # Submit form or wait for validation
            page.wait_for_timeout(2000)

        # Continue scraping
        data = extract_data(page)
        browser.close()
        return data

Worth noting is that CAPTCHA solving costs money—typically $1-3 per 1000 solves. Budget accordingly. Learn about different CAPTCHA types to choose the right solving approach.


Scaling Up: Scraping Thousands of Pages Efficiently

Single-page scraping is straightforward. Scaling to thousands of URLs requires different strategies.

Concurrent Scraping with Multiple Browser Instances

Python’s ThreadPoolExecutor lets you run multiple Playwright instances in parallel:

PYTHON
from concurrent.futures import ThreadPoolExecutor, as_completed
from playwright.sync_api import sync_playwright
import time

def scrape_single_url(url):
    """
    Scrapes a single URL (runs in separate thread)
    """
    with sync_playwright() as p:
        try:
            browser = p.chromium.launch(headless=True)
            page = browser.new_page()

            page.goto(url, timeout=30000)

            data = {
                'url': url,
                'title': page.title(),
                'status': 'success'
            }

            browser.close()
            return data

        except Exception as e:
            return {'url': url, 'error': str(e), 'status': 'failed'}

def scrape_urls_concurrently(urls, max_workers=5):
    """
    Scrapes multiple URLs concurrently
    """
    results = []

    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        # Submit all tasks
        future_to_url = {executor.submit(scrape_single_url, url): url for url in urls}

        # Process completed tasks
        for future in as_completed(future_to_url):
            url = future_to_url[future]
            try:
                data = future.result()
                results.append(data)
                print(f'Completed: {url}')
            except Exception as e:
                print(f'Failed: {url} - {e}')

    return results

# Example usage
urls = [f'https://example.com/page/{i}' for i in range(100)]
results = scrape_urls_concurrently(urls, max_workers=10)

# Analyze results
successful = [r for r in results if r['status'] == 'success']
failed = [r for r in results if r['status'] == 'failed']

print(f'\nSuccessfully scraped: {len(successful)}/{len(urls)}')
print(f'Failed: {len(failed)}')

Keep in mind that each browser instance consumes 150-300MB of RAM. Don’t overwhelm your system by launching too many at once.

Using Browser Contexts for Memory Efficiency

Instead of launching new browsers, reuse one browser with multiple contexts:

PYTHON
def scrape_with_contexts(urls):
    """
    More memory-efficient scraping using browser contexts
    """
    results = []

    with sync_playwright() as p:
        # Launch browser once
        browser = p.chromium.launch(headless=True)

        for url in urls:
            # Create isolated context for each URL
            context = browser.new_context()
            page = context.new_page()

            try:
                page.goto(url, timeout=30000)
                data = {'url': url, 'title': page.title()}
                results.append(data)
            except Exception as e:
                print(f'Error with {url}: {e}')
            finally:
                # Always close context to free memory
                context.close()

        browser.close()

    return results

Browser contexts share the browser process but maintain separate cookies, cache, and storage. This uses significantly less memory than multiple browser instances.

Handling Pagination Like a Pro

Most sites paginate their content. Here are patterns for scraping all pages:

URL-based pagination:

PYTHON
def scrape_paginated_site(base_url, max_pages=None):
    """
    Scrapes sites with page numbers in URL
    """
    all_results = []
    page_num = 1

    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page()

        while True:
            url = f'{base_url}?page={page_num}'
            print(f'Scraping page {page_num}...')

            page.goto(url)

            # Extract items from current page
            items = page.query_selector_all('.item')

            if not items:
                print('No more items found')
                break

            for item in items:
                data = extract_item_data(item)
                all_results.append(data)

            # Check if we've reached max pages
            if max_pages and page_num >= max_pages:
                break

            # Check if "Next" button exists
            next_button = page.query_selector('a.next-page')
            if not next_button or 'disabled' in next_button.get_attribute('class'):
                print('Reached last page')
                break

            page_num += 1
            time.sleep(random.uniform(1, 3))

        browser.close()

    return all_results

Click-based pagination (Load More buttons):

PYTHON
def scrape_load_more_pagination(url):
    """
    Scrapes sites with "Load More" buttons
    """
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        page = browser.new_page()

        page.goto(url)
        all_items = []

        while True:
            # Wait for items to load
            page.wait_for_selector('.item')

            # Get current items count
            items = page.query_selector_all('.item')
            previous_count = len(all_items)
            current_count = len(items)

            print(f'Found {current_count} items total')

            # Look for "Load More" button
            load_more = page.query_selector('button:has-text("Load More")')

            if not load_more or not load_more.is_visible():
                print('No more content to load')
                break

            # Click and wait for new content
            load_more.click()
            page.wait_for_timeout(2000)

            # Check if new items appeared
            new_items = page.query_selector_all('.item')
            if len(new_items) == current_count:
                print('No new items loaded, stopping')
                break

        # Extract all items
        final_items = page.query_selector_all('.item')
        for item in final_items:
            data = extract_item_data(item)
            all_items.append(data)

        browser.close()
        return all_items

Speed up your web scraping with these pagination strategies.


Playwright vs The Competition: Honest Comparison

You’ve got options for browser automation. Let’s see how Playwright stacks up against alternatives.

Playwright vs Selenium: The Old Guard vs The New

❮ Swipe table left/right ❯
FeaturePlaywrightSelenium
SpeedFast (20-30% faster)Slower
SetupSimple (pip install playwright)Complex (drivers needed)
Auto-WaitingBuilt-in, automaticManual or explicit waits
Browser SupportChrome, Firefox, SafariChrome, Firefox, Safari, IE, Edge
Language SupportPython, JS, Java, C#Python, JS, Java, Ruby, C#, PHP
Learning CurveModerateSteep
CommunityGrowing (69k GitHub stars)Massive (31k GitHub stars)
DocumentationExcellent, modernExtensive but dated
MaintenanceActive (Microsoft)Community-driven

Bottom line: Playwright is faster and easier for web scraping. Selenium has a larger community and more Stack Overflow answers. For new projects in 2026, I’d choose Playwright. Read the full Playwright vs Selenium comparison.

Playwright vs Puppeteer: Microsoft vs Google

❮ Swipe table left/right ❯
FeaturePlaywrightPuppeteer
Browser SupportChrome, Firefox, SafariChrome, Firefox (limited)
Language SupportPython, JS, Java, C#JavaScript only
PerformanceExcellentExcellent (slightly faster)
API DesignModern, consistentModern, Chrome-focused
Mobile EmulationBuilt-inBuilt-in
Network InterceptionAdvancedAdvanced
CommunityMedium (69k stars)Large (90k stars)

Bottom line: If you only need JavaScript and Chrome, Puppeteer is fine. If you want multi-browser support or prefer Python, Playwright wins. Performance-wise, they’re nearly identical.

Playwright vs BeautifulSoup: Apples and Oranges

This comparison comes up a lot, but it’s not really fair. BeautifulSoup is an HTML parser, not a browser automation tool. Here’s when to use each:

Use BeautifulSoup when:

  • Scraping static HTML pages
  • Speed is critical (it’s 10-50x faster than Playwright)
  • Content doesn’t require JavaScript
  • You’re parsing HTML you already have
  • Learn BeautifulSoup basics

Use Playwright when:

  • Content loads dynamically via JavaScript
  • You need to interact with pages (clicking, scrolling)
  • Handling authentication or sessions
  • Scraping SPAs (Single Page Applications)
  • Need screenshots or PDF generation

In practice, many scrapers use both: Playwright to render the page, then BeautifulSoup to parse the HTML. Best of both worlds.


Production-Ready Scraping: Error Handling, Logging, and Monitoring

Moving from hobby scripts to production systems requires robust error handling and monitoring.

Implementing Smart Retry Logic

Networks fail. Servers timeout. Pages crash. Your scraper needs to handle this gracefully:

PYTHON
import time
import logging
from functools import wraps

def retry_on_failure(max_attempts=3, backoff_factor=2, exceptions=(Exception,)):
    """
    Decorator for retrying functions with exponential backoff
    """
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            attempt = 1
            while attempt <= max_attempts:
                try:
                    return func(*args, **kwargs)
                except exceptions as e:
                    if attempt == max_attempts:
                        logging.error(f'Failed after {max_attempts} attempts: {e}')
                        raise

                    wait_time = backoff_factor ** attempt
                    logging.warning(f'Attempt {attempt} failed: {e}. Retrying in {wait_time}s...')
                    time.sleep(wait_time)
                    attempt += 1
        return wrapper
    return decorator

@retry_on_failure(max_attempts=3, backoff_factor=2)
def scrape_with_retry(url):
    """
    Scrapes URL with automatic retry on failure
    """
    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page()

        page.goto(url, timeout=30000)
        data = extract_data(page)

        browser.close()
        return data

# Usage
try:
    data = scrape_with_retry('https://example.com')
except Exception as e:
    logging.error(f'Scraping failed completely: {e}')

Exponential backoff prevents hammering servers during temporary issues while giving them time to recover.

Comprehensive Logging for Debugging

Production scrapers need detailed logs. Here’s a production-grade logging setup:

PYTHON
import logging
from datetime import datetime
import os

def setup_logging(log_dir='logs'):
    """
    Sets up comprehensive logging configuration
    """
    # Create logs directory if it doesn't exist
    os.makedirs(log_dir, exist_ok=True)

    # Log filename with timestamp
    log_file = os.path.join(log_dir, f'scraper_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log')

    # Configure logging
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.FileHandler(log_file),
            logging.StreamHandler()  # Also print to console
        ]
    )

    return logging.getLogger(__name__)

logger = setup_logging()

def scrape_with_logging(url):
    """
    Scraper with comprehensive logging
    """
    logger.info(f'Starting scrape of {url}')

    try:
        with sync_playwright() as p:
            logger.debug('Launching browser')
            browser = p.chromium.launch()

            logger.debug('Creating new page')
            page = browser.new_page()

            logger.info(f'Navigating to {url}')
            page.goto(url)

            logger.debug('Waiting for content to load')
            page.wait_for_selector('.item')

            logger.info('Extracting data')
            items = page.query_selector_all('.item')
            logger.info(f'Found {len(items)} items')

            data = [extract_item_data(item) for item in items]

            logger.info(f'Successfully scraped {len(data)} items from {url}')

            browser.close()
            return data

    except Exception as e:
        logger.error(f'Error scraping {url}: {e}', exc_info=True)
        raise

These logs help you debug issues in production and track scraper performance over time.

Monitoring Scraper Health

For long-running scrapers, implement health monitoring:

PYTHON
import json
from datetime import datetime

class ScraperMonitor:
    def __init__(self, stats_file='scraper_stats.json'):
        self.stats_file = stats_file
        self.stats = self.load_stats()

    def load_stats(self):
        """Load existing stats or create new"""
        try:
            with open(self.stats_file, 'r') as f:
                return json.load(f)
        except FileNotFoundError:
            return {
                'total_requests': 0,
                'successful_requests': 0,
                'failed_requests': 0,
                'start_time': datetime.now().isoformat(),
                'errors': []
            }

    def save_stats(self):
        """Save stats to file"""
        with open(self.stats_file, 'w') as f:
            json.dump(self.stats, f, indent=2)

    def record_success(self, url):
        """Record successful scrape"""
        self.stats['total_requests'] += 1
        self.stats['successful_requests'] += 1
        self.save_stats()

    def record_failure(self, url, error):
        """Record failed scrape"""
        self.stats['total_requests'] += 1
        self.stats['failed_requests'] += 1
        self.stats['errors'].append({
            'url': url,
            'error': str(error),
            'timestamp': datetime.now().isoformat()
        })
        self.save_stats()

    def get_success_rate(self):
        """Calculate success rate"""
        if self.stats['total_requests'] == 0:
            return 0
        return (self.stats['successful_requests'] / self.stats['total_requests']) * 100

# Usage
monitor = ScraperMonitor()

def scrape_with_monitoring(url):
    try:
        data = scrape_url(url)
        monitor.record_success(url)
        return data
    except Exception as e:
        monitor.record_failure(url, e)
        raise

# Check health periodically
print(f"Success rate: {monitor.get_success_rate():.2f}%")

Real-World Use Cases: Practical Scraping Applications

Let’s look at concrete examples of what you can build with Playwright.

E-commerce Price Monitoring System

Track competitor prices automatically:

PYTHON
import json
from datetime import datetime

def monitor_product_prices():
    """
    Monitors prices for a list of products
    """
    products_to_track = [
        {
            'name': 'iPhone 15 Pro',
            'url': 'https://store.com/iphone-15-pro',
            'selector': '.price-current'
        },
        {
            'name': 'MacBook Pro M3',
            'url': 'https://store.com/macbook-pro-m3',
            'selector': '.product-price'
        }
    ]

    price_history = []

    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        page = browser.new_page()

        for product in products_to_track:
            try:
                logger.info(f"Checking price for {product['name']}")

                page.goto(product['url'])
                page.wait_for_selector(product['selector'])

                price_element = page.query_selector(product['selector'])
                price_text = price_element.inner_text()

                # Extract numeric price
                import re
                price_match = re.search(r'[\d,]+\.?\d*', price_text)
                price = float(price_match.group().replace(',', '')) if price_match else None

                price_history.append({
                    'product': product['name'],
                    'price': price,
                    'url': product['url'],
                    'timestamp': datetime.now().isoformat()
                })

                logger.info(f"Current price for {product['name']}: ${price}")

            except Exception as e:
                logger.error(f"Error checking {product['name']}: {e}")

        browser.close()

    # Save price history
    with open(f'price_history_{datetime.now().strftime("%Y%m%d")}.json', 'w') as f:
        json.dump(price_history, f, indent=2)

    return price_history

# Run daily to track price changes
prices = monitor_product_prices()

Learn why businesses use web scraping for competitive intelligence.

Job Listing Aggregator

Collect job postings from multiple sites:

PYTHON
def scrape_job_listings(search_term, location):
    """
    Scrapes job listings for given search criteria
    """
    all_jobs = []

    with sync_playwright() as p:
        browser = p.chromium.launch()
        page = browser.new_page()

        # Build search URL
        url = f'https://jobsite.com/jobs?q={search_term}&l={location}'
        page.goto(url)

        # Wait for listings to load
        page.wait_for_selector('.job-card')

        # Scroll to load more listings
        for _ in range(5):
            page.evaluate('window.scrollBy(0, window.innerHeight)')
            page.wait_for_timeout(1000)

        # Extract job data
        job_cards = page.query_selector_all('.job-card')

        for card in job_cards:
            try:
                job = {
                    'title': card.query_selector('.job-title').inner_text(),
                    'company': card.query_selector('.company-name').inner_text(),
                    'location': card.query_selector('.job-location').inner_text(),
                    'salary': card.query_selector('.salary-info').inner_text() if card.query_selector('.salary-info') else 'Not specified',
                    'posted_date': card.query_selector('.posted-date').inner_text(),
                    'link': card.query_selector('a').get_attribute('href')
                }
                all_jobs.append(job)
            except Exception as e:
                logger.warning(f'Error extracting job: {e}')

        browser.close()

    logger.info(f'Found {len(all_jobs)} job listings')
    return all_jobs

# Usage
jobs = scrape_job_listings('Python Developer', 'New York')

Social Media Content Collection

Extract public posts and profiles (only for authorized, public data):

PYTHON
def scrape_public_profile(profile_url):
    """
    Scrapes public profile information
    (Only use for publicly available data with permission)
    """
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        page = browser.new_page()

        page.goto(profile_url)
        page.wait_for_timeout(3000)

        # Scroll to load more posts
        for _ in range(5):
            page.evaluate('window.scrollBy(0, window.innerHeight)')
            page.wait_for_timeout(2000)

        # Extract profile data
        profile_data = {
            'username': page.query_selector('.username').inner_text(),
            'bio': page.query_selector('.bio').inner_text() if page.query_selector('.bio') else '',
            'follower_count': page.query_selector('.followers').inner_text(),
            'posts': []
        }

        # Extract recent posts
        post_elements = page.query_selector_all('.post-item')[:10]  # First 10 posts

        for post in post_elements:
            try:
                post_data = {
                    'text': post.query_selector('.post-text').inner_text(),
                    'timestamp': post.query_selector('.post-time').inner_text(),
                    'likes': post.query_selector('.like-count').inner_text()
                }
                profile_data['posts'].append(post_data)
            except:
                pass

        browser.close()
        return profile_data

Remember to respect ethical web scraping guidelines and only scrape public data with appropriate permissions.

Frequently Asked Questions

Can Playwright Be Detected by Websites?

Yes, Playwright can be detected, but you can reduce detection significantly with proper configuration. Out of the box, Playwright leaves fingerprints like navigator.webdriver returning true and distinctive browser properties. However, combining the Playwright Stealth plugin, custom User-Agents, realistic behavior patterns, and proxies bypasses most detection systems.

From my testing, properly configured Playwright gets past about 70-80% of sites with moderate protection. Sites with enterprise-level anti-bot systems (like LinkedIn or major banks) are tougher and may require additional techniques. The key here is layering multiple anti-detection methods rather than relying on any single trick.

Is Playwright Faster Than Selenium for Web Scraping?

Yes, Playwright is measurably faster than Selenium in most scenarios—typically 20-30% quicker. Playwright uses the DevTools Protocol directly, while Selenium uses the older WebDriver protocol that adds latency. Additionally, Playwright’s auto-waiting mechanism eliminates the need for manual delays that slow down Selenium scripts.

In practical terms, scraping 1000 pages might take 3 hours with Selenium but only 2-2.5 hours with Playwright. The performance gap widens with complex pages that have lots of JavaScript. That said, Selenium still has the largest community and most comprehensive documentation, so you’ll find more help when stuck.

Does Playwright Work on All Operating Systems?

Yes, Playwright runs on Windows, macOS, and Linux. Installation is identical across platforms, though Linux may require additional system dependencies. Run playwright install-deps on Linux to automatically install required libraries.

Worth noting is that Playwright performs best on Linux servers for production deployments. Most cloud providers offer Ubuntu or Debian images that work perfectly. If you’re developing on Windows or Mac locally, everything works fine for testing before deploying to Linux servers.

How Much RAM Do I Need for Running Playwright?

Each Playwright browser instance consumes approximately 150-300MB of RAM. A machine with 8GB RAM can comfortably run 15-20 concurrent browser instances. For production scraping at scale, plan on 16GB or more.

Keep in mind that memory usage increases with:

  • Number of open tabs/pages
  • Complexity of websites (heavy JavaScript sites use more)
  • Duration of sessions (memory can accumulate over time)
  • Screenshots and PDF generation

If you’re running out of memory, consider using browser contexts instead of separate browser instances—they share resources more efficiently.

Can You Use Playwright Without Programming Knowledge?

No, Playwright requires actual programming skills to use effectively. Unlike no-code scraping tools with visual interfaces, Playwright is a code framework. You’ll need at least intermediate-level knowledge of Python, JavaScript, Java, or C# to write functional scrapers.

The good news? Playwright’s API is intuitive and well-documented. If you understand basic programming concepts (variables, loops, functions, error handling), you’ll pick it up relatively quickly. Start with simple scraping tasks and gradually tackle more complex scenarios. The examples in this guide provide templates you can adapt for your needs.

Web scraping legality depends on what you scrape, how you scrape it, and what you do with the data—not the tool you use. Playwright itself is completely legal. However, you must:

  • Respect websites’ robots.txt files
  • Follow terms of service
  • Only scrape publicly available data
  • Not overwhelm servers with requests
  • Respect copyright and data privacy laws

Read about web scraping legality for comprehensive guidance. When in doubt, consult a lawyer before scraping commercial websites at scale.

How Do You Handle Rate Limiting with Playwright?

Implement delays between requests and rotate IPs through proxies. Rate limiting occurs when servers detect too many requests from the same IP in a short time. Combat this with:

  1. Random delays: Add 2-5 second pauses between requests
  2. Proxy rotation: Distribute requests across multiple IPs
  3. Respect headers: Check Retry-After headers when encountering 429 errors
  4. Session management: Maintain cookies and sessions to appear like normal users

Understanding rate limiting helps you design respectful scrapers that don’t trigger bans.

What’s the Cost of Scraping at Scale with Playwright?

The main costs are infrastructure and proxies. Playwright itself is free, but running it at scale requires:

Infrastructure costs:

  • Cloud server with 16GB RAM: $50-150/month
  • Storage for scraped data: $5-20/month

Proxy costs:

  • Residential proxies: $5-15 per GB (most reliable)
  • Datacenter proxies: $1-3 per GB (faster but easier to detect)
  • Mobile proxies: $20-50 per GB (highest success rate)

CAPTCHA solving (if needed):

  • $1-3 per 1000 CAPTCHAs solved

For scraping 10,000 pages daily, budget $200-500/month total. Scale up or down based on your needs.

Conclusion: Your Next Steps with Playwright

You’ve made it through this comprehensive guide—congrats! You now understand how Playwright works, why it’s powerful for web scraping, and how to build production-ready scrapers that handle dynamic content, bypass basic anti-bot systems, and scale to thousands of pages.

Here’s what makes Playwright the right choice for modern web scraping: it sees websites exactly how users see them, handles JavaScript naturally, supports multiple browsers with identical code, and provides intuitive APIs that just work. Unlike older tools that feel clunky and require constant babysitting, Playwright’s auto-waiting and built-in features make scraping dynamic sites actually enjoyable.

Start small. Build a simple scraper for one website, get comfortable with selectors and waiting strategies, then gradually add proxy rotation, anti-detection techniques, and concurrent scraping. Most importantly, scrape responsibly—respect robots.txt, add reasonable delays, and only collect publicly available data.

The web scraping landscape keeps evolving. Sites get smarter about detecting bots, but tools like Playwright keep improving too. Keep learning, test your scrapers regularly, and stay updated with web scraping best practices.

Ready to take your scraping to the next level? Experiment with the code examples in this guide, adapt them to your specific needs, and start extracting the data that’ll power your projects. Happy scraping!

Data Prixa

Data Prixa

Dataprixa is an independent editorial platform focused on data infrastructure and security insights. The content published under this author explores web scraping, data collection, proxy networks, and cybersecurity technologies with an emphasis on clarity, ethical practices, and long-term relevance. Articles are written to support developers, researchers, and modern businesses in understanding data-driven systems and secure infrastructure.