Playwright: How to Intercept and Modify Network Requests

UNDETECTED LABS6 MIN READ
On this page

Playwright can do more than click buttons and read the DOM. With page.route() every request the page sends passes through your code first, and you choose what happens to it: send it on, drop it, change it or answer it yourself.

What interception gives you

A single page load sends dozens of requests for HTML, CSS, scripts, images, API calls and analytics. A route handler sits between the browser and the network and sees each one:

Browser → [your route handler] → Server

Scrapers use it to read the JSON an app loads instead of parsing HTML, and to skip images and trackers. Tests use it to fake the backend. When a page misbehaves, logging every request it makes is often the fastest way to see why.

Setup

Playwright 1.65 needs Python 3.10 or newer.

pip install playwright
playwright install chromium

Logging every request

page.route() takes a URL pattern with wildcards and a handler function.

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()

        # Intercept all requests
        async def handle_request(route):
            print(f'Request: {route.request.method} {route.request.url}')
            await route.continue_()  # let it through

        await page.route('**/*', handle_request)
        await page.goto('https://example.com')
        await browser.close()

asyncio.run(main())

route.continue_() sends the request on unchanged. A handler has to finish every request with continue_(), abort() or fulfill(). If it returns without calling one, that request stays pending and the page waits for it.

Blocking requests

Most scrapers don’t need images, fonts or analytics, and dropping them makes pages load faster.

import asyncio
from playwright.async_api import async_playwright

BLOCKED_TYPES = {'image', 'font', 'media', 'stylesheet'}
BLOCKED_DOMAINS = {'google-analytics.com', 'googletagmanager.com', 'hotjar.com', 'facebook.net'}

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()

        async def block_resources(route):
            request = route.request
            resource_type = request.resource_type
            url = request.url

            # Block by resource type
            if resource_type in BLOCKED_TYPES:
                await route.abort()
                return

            # Block by domain
            if any(domain in url for domain in BLOCKED_DOMAINS):
                await route.abort()
                return

            await route.continue_()

        await page.route('**/*', block_resources)
        await page.goto('https://example.com')

        print(await page.title())
        await browser.close()

asyncio.run(main())

How much time this saves depends on the site, so measure it on yours. Be careful with stylesheet: some pages hide content until their CSS loads, and a script that waits for an element to be visible will then time out.

Capturing API responses

On many sites the HTML arrives nearly empty and the content comes later as JSON from an API. You can take that JSON straight from the response and skip parsing the rendered page.

import asyncio
import json
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()

        captured_data = []

        async def capture_api(route):
            request = route.request

            # Only intercept API calls
            if '/api/' in request.url:
                # Let the request through, then capture the response
                response = await route.fetch()
                body = await response.json()
                captured_data.append({
                    'url': request.url,
                    'data': body
                })
                await route.fulfill(response=response)
                return

            await route.continue_()

        await page.route('**/*', capture_api)
        await page.goto('https://example.com/products')
        await page.wait_for_load_state('networkidle')

        print(json.dumps(captured_data, indent=2))
        await browser.close()

asyncio.run(main())

route.fetch() sends the request and returns the response to you, and route.fulfill(response=response) hands it on to the page. fetch() sends the browser context’s cookies along, so requests that need a login keep working.

Modifying requests

route.continue_() accepts new headers, a new URL, a method or a POST body.

Adding or overriding headers

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()

        async def add_auth_header(route):
            headers = {
                **route.request.headers,
                'Authorization': 'Bearer your_token_here',
                'X-Custom-Header': 'my-value',
            }
            await route.continue_(headers=headers)

        await page.route('**/api/**', add_auth_header)
        await page.goto('https://example.com/dashboard')
        await browser.close()

asyncio.run(main())

Changing the request URL

async def redirect_request(route):
    url = route.request.url

    # Redirect staging to production
    if 'staging.example.com' in url:
        new_url = url.replace('staging.example.com', 'example.com')
        await route.continue_(url=new_url)
        return

    await route.continue_()

The new URL has to use the same protocol as the old one; you can’t switch http to https here.

Mocking API responses

In tests you can answer an API call yourself and never touch the real backend. The test then doesn’t fail when staging is down.

import asyncio
import json
from playwright.async_api import async_playwright

MOCK_PRODUCTS = [
    {'id': 1, 'name': 'Widget A', 'price': 29.99},
    {'id': 2, 'name': 'Widget B', 'price': 49.99},
]

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()

        async def mock_api(route):
            if '/api/products' in route.request.url:
                await route.fulfill(
                    status=200,
                    content_type='application/json',
                    body=json.dumps(MOCK_PRODUCTS)
                )
                return

            await route.continue_()

        await page.route('**/*', mock_api)
        await page.goto('https://example.com/shop')

        # The page will receive your mock data instead of hitting the real API
        await browser.close()

asyncio.run(main())

Error responses work the same way. Return a 500 to check what the page shows when the API breaks:

async def mock_error(route):
    if '/api/user' in route.request.url:
        await route.fulfill(
            status=500,
            body='Internal Server Error'
        )
        return
    await route.continue_()

Modifying responses

You can also fetch the real response, change a field and give the page the edited version:

import asyncio
import json
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()

        async def modify_response(route):
            if '/api/config' in route.request.url:
                response = await route.fetch()
                data = await response.json()

                # Modify a field in the response
                data['feature_flags']['dark_mode'] = True

                await route.fulfill(
                    status=response.status,
                    headers=dict(response.headers),
                    body=json.dumps(data)
                )
                return

            await route.continue_()

        await page.route('**/*', modify_response)
        await page.goto('https://example.com')
        await browser.close()

asyncio.run(main())

Catching one response with expect_response

If you need one response and nothing else, page.expect_response() is shorter than a route handler. It doesn’t intercept anything: the request goes through as usual and you get a copy of the response.

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        page = await browser.new_page()

        # Wait for a specific API call that happens during navigation
        async with page.expect_response('**/api/user/profile') as response_info:
            await page.goto('https://example.com/dashboard')

        response = await response_info.value
        data = await response.json()
        print(data)

        await browser.close()

asyncio.run(main())

Routing for a whole context

context.route() applies to every page in the browser context, including pages opened later and popups.

import asyncio
from playwright.async_api import async_playwright

async def main():
    async with async_playwright() as p:
        browser = await p.chromium.launch()
        context = await browser.new_context()

        # This applies to every page opened in this context
        await context.route('**/*.{png,jpg,jpeg,gif,webp,svg}', lambda route: route.abort())

        page1 = await context.new_page()
        page2 = await context.new_page()

        await page1.goto('https://example.com')
        await page2.goto('https://example.org')

        await browser.close()

asyncio.run(main())

Which method to call

What you want Method
Block images/fonts/ads route.abort()
Pass request through unchanged route.continue_()
Return fake data route.fulfill()
Capture real response route.fetch() then route.fulfill()
Add/change headers route.continue_(headers=...)
One-off response capture page.expect_response()

A scraper that puts it together

This one drops images, fonts and CSS, and collects product data from the API the page calls:

import asyncio
import json
from playwright.async_api import async_playwright

async def scrape_products(url: str) -> list:
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=True)
        page = await browser.new_page()

        products = []

        async def handle_route(route):
            request = route.request

            # Block resources we don't need
            if request.resource_type in {'image', 'font', 'stylesheet', 'media'}:
                await route.abort()
                return

            # Capture product API responses
            if '/api/products' in request.url:
                response = await route.fetch()
                try:
                    data = await response.json()
                    if isinstance(data, list):
                        products.extend(data)
                    elif 'items' in data:
                        products.extend(data['items'])
                except Exception:
                    pass
                await route.fulfill(response=response)
                return

            await route.continue_()

        await page.route('**/*', handle_route)
        await page.goto(url)
        await page.wait_for_load_state('networkidle')

        await browser.close()
        return products

products = asyncio.run(scrape_products('https://example.com/shop'))
print(f'Found {len(products)} products')
print(json.dumps(products[:3], indent=2))

The JSON keeps the API’s field names and types, so a redesign of the page’s HTML won’t break the scraper. If the site changes its API, you will have to update the parsing.

Common problems

The page hangs on some requests. Your handler has a path that returns without calling continue_(), abort() or fulfill(). Calling fetch() alone doesn’t count, because the page still waits until you fulfill.

The page breaks after you add a route. The pattern **/* catches everything, including scripts the page needs. Start with a narrow pattern such as **/api/** and widen it once that works.