To reduce unnecessary browser downloads, use Playwright request routing to abort resources your extraction task does not need. Start with a small, explicit set such as images, fonts or media, then check that the same records and required fields still reach your output. A page that opens successfully can still have missing data.

There is an important measurement trap: enabling Playwright routing disables the HTTP cache, even when the handler continues every request. Compare three conditions—normal loading, routing with everything allowed, and routing with selected types blocked—before attributing a change to blocking. The BrowserContext routing reference documents both the cache behavior and the routing API.

This guide is for a task that already needs browser execution. If a permitted data endpoint can supply the required records directly, first consider the simpler path in Requests, Playwright, and reliable pagination. Here, the task is changing what the browser loads while preserving its extraction result.

Decide which resources your task actually needs

A resource is optional only in relation to the result you want. Images may be unnecessary when collecting text descriptions, but essential for a visual audit. A font can affect layout and a screenshot comparison. A media request can be part of the dataset rather than decoration.

Keep documents, scripts, stylesheets, Fetch and XHR available in the first experiment. Scripts may construct the page, stylesheets may affect visibility and interaction, and Fetch or XHR may carry the records. Do not block all requests outside the main domain: authorized applications can depend on separate asset and API hosts.

Use route.request.resource_type rather than relying only on a file extension. A URL ending in .jpg is not a complete inventory of image requests, and a URL without an extension may still return an image. Playwright's network guide shows how to inspect request types and abort selected requests.

Before writing the rule, define the page actions and fields that must continue to work. Include required identifiers, names, prices or other task-specific values. Define the expected record count from a controlled fixture or a trusted reference, rather than assuming the baseline is complete simply because it produced output.

Separate the blocking effect from the routing effect

Use the same browser version, locale, viewport policy, session state and extraction contract in each condition:

ConditionRoute handlerSelected resourcesPurpose
NormalNot installedAllowedEstablish ordinary browser behavior
PassInstalledAll allowedObserve the effect of routing itself
BlockInstalledSelected types abortedCompare blocking against the pass condition

Compare pass versus block to isolate the selected blocking rules. Compare normal versus block to judge the proposed workflow as a whole. Both comparisons matter because a workflow can reduce some downloads while losing useful cache reuse.

For repeat-visit workloads, repeat the actual navigation sequence within each condition's context as a separate experiment. Three fresh contexts are useful for the first correctness check; they do not measure the value of a warm HTTP cache over a long-running job.

The script below blocks Service Workers in all three conditions. Playwright warns that requests handled by a Service Worker are not intercepted by browser_context.route(). Using the same setting keeps that policy consistent across the experiment. If your application needs a Service Worker, blocking it changes the application: design and validate a separate test instead of assuming these results represent normal production behavior.

Run a script that rejects changed records

Use Python 3.11 or newer and install Playwright plus its Chromium browser in your own project environment:

python -m pip install playwright
python -m playwright install chromium

Adapt these selectors to an authorized page before running the script. This example expects a visible [data-testid="data-ready"] marker only after all required records are ready. Every [data-testid="record"] must have a nonempty data-id, with child elements for name and price. Those names are a teaching contract, not selectors for an existing public website.

Save this as playwright_blocking.py:

import argparse
import json
from collections import Counter
from playwright.sync_api import sync_playwright


def collect(browser, url, mode, expected_count, blocked_types):
    # Identical state policy in all three arms of this experiment.
    context = browser.new_context(service_workers="block", locale="en-US")
    context.set_default_timeout(15000)
    blocked = Counter()
    completed = Counter()
    failed = Counter()
    http_errors = []

    def handle_route(route):
        kind = route.request.resource_type
        if mode == "block" and kind in blocked_types:
            blocked[kind] += 1
            route.abort()
        else:
            route.continue_()

    if mode in {"pass", "block"}:
        context.route("**/*", handle_route)
    page = context.new_page()
    page.on("requestfinished", lambda r: completed.update([r.resource_type]))
    page.on("requestfailed", lambda r: failed.update([r.resource_type]))
    page.on("response", lambda r: http_errors.append(r.status)
            if r.status >= 400 else None)
    try:
        response = page.goto(url, wait_until="domcontentloaded")
        if response is None or response.status != 200:
            raise RuntimeError("Main document did not return HTTP 200")
        # Adapt this contract to your authorized page before running.
        page.locator('[data-testid="data-ready"]').wait_for(state="visible")
        cards = page.locator('[data-testid="record"]')
        rows = []
        for card in cards.all():
            row = {
                "id": card.get_attribute("data-id"),
                "name": card.locator('[data-testid="name"]').inner_text().strip(),
                "price": card.locator('[data-testid="price"]').inner_text().strip(),
            }
            if not all(row.values()):
                raise RuntimeError("Required field is empty")
            rows.append(row)
        if len(rows) != expected_count:
            raise RuntimeError("Record count differs from the expected fixture")
        if len({row["id"] for row in rows}) != len(rows):
            raise RuntimeError("Duplicate record IDs")
        # Finish initial loads so request completion counters are comparable.
        page.wait_for_load_state("load")
        return {
            "mode": mode,
            "rows": sorted(rows, key=lambda row: row["id"]),
            "blocked": dict(blocked),
            "completed": dict(completed),
            "failed": dict(failed),
            "http_errors": http_errors,
        }
    finally:
        context.close()


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("url")
    parser.add_argument("--expected-count", type=int, required=True)
    parser.add_argument("--block", nargs="*", default=["image", "font", "media"])
    args = parser.parse_args()
    allowed = {"image", "font", "media"}
    if not set(args.block) <= allowed:
        parser.error("Start with image, font and media only")
    with sync_playwright() as p:
        browser = p.chromium.launch()
        try:
            results = [collect(browser, args.url, mode, args.expected_count,
                               set(args.block))
                       for mode in ("normal", "pass", "block")]
            if any(r["rows"] != results[0]["rows"] for r in results[1:]):
                raise RuntimeError("Extraction changed: reject this rule set")
            print(json.dumps(results, indent=2))
        finally:
            browser.close()


if __name__ == "__main__":
    main()

The script deliberately uses one route handler. route.abort() rejects the selected request and route.continue_() allows the other requests to proceed. Every matched request must receive an action; leaving a route unresolved can stall the operation. In a larger application, check for existing page routes too: Playwright gives matching page routes precedence over context routes.

No proxy is configured in this teaching script. If you use a proxy, add your approved Playwright proxy configuration identically for every condition and compare the same region and session policy. Keep credentials outside the source file and logs. Session choices matter independently of the exit address; see HTTP cookies before adapting the example to signed-in workflows.

Read the output before widening the rule

For a controlled two-record page, the command takes this form:

python playwright_blocking.py 'https://your-authorized-site.example/list' --expected-count 2

Replace the placeholder address and expected count. If any required field is empty, an identifier is duplicated, a record count is wrong, or rows differ between conditions, the script raises an error. If the comparison succeeds, it prints the rows and request counters for each condition. The command is an invocation example, not a report that the placeholder site was tested.

The example has been checked for Python syntax and reviewed against Playwright's documented routing behavior. It has not been executed in a browser against a production site or used to measure a proxy bill. Verify it with your own controlled page and installed Playwright version before adopting it.

The counters answer different questions:

  • blocked counts deliberate abort decisions by resource type.
  • completed counts requests whose response bodies completed during the observed workflow.
  • failed includes deliberately aborted requests as well as other request failures.
  • http_errors records observed HTTP responses with status 400 or above; Playwright does not classify an HTTP 404 or 503 as a network request failure.

Investigate new HTTP errors and failed requests that do not correspond to your intended blocks. A matching set of extracted rows is necessary, but it is not enough if the workflow also needs a working filter, detail view, screenshot or download. Add those actual actions and their acceptance checks before calling the job successful.

The script waits for a task-specific readiness marker and the initial load event. It does not claim to capture every background request a page might issue later. Applications that poll continuously or update after an interaction need a defined observation window tied to that task.

Measure traffic separately from request counts

Aborting ten small images and aborting one large video are different transfer changes. Request counts alone cannot tell you transferred bytes or billed usage. A completed response can also have come from cache, so the completion counter is not a wire-traffic meter.

For a traffic comparison, use browser network transfer observations and the proxy provider's documented usage measurement over the same completed task. Hold the page set, interaction sequence, region, retry policy and success criteria constant. Report the absolute transfer and number of complete results for each condition before calculating a percentage.

The existing guide to measuring proxy traffic per task covers the billing question. This workflow supplies the missing correctness check: reject a lower-traffic run if it produces fewer usable records or breaks a required page action. There is no universal savings percentage for resource blocking.

Roll back one resource type at a time

If the broad initial set fails, restore normal loading and confirm the same fixture still works. Then allow images while leaving the other initial candidates blocked:

python playwright_blocking.py 'https://your-authorized-site.example/list' --expected-count 2 --block font media

If the result recovers, investigate whether image loading triggers a required update or whether the task actually needs image content. Repeat with other small sets rather than adding more timeout or retry logic around a broken rule.

An empty block list creates a block condition that continues everything:

python playwright_blocking.py 'https://your-authorized-site.example/list' --expected-count 2 --block

This is a useful handler check, but routing still remains enabled in that condition. For the ordinary cache-enabled baseline, use a fresh context without installing a route, as the normal condition does. Keep your previous working configuration so a failed experiment can return to it cleanly.

Frequently asked questions

Should I block stylesheets as well?

Only after proving they are unnecessary for the full task. Styles can affect visibility, layout and clickable controls. Start with a smaller resource set and test the required interactions before expanding it.

Why do some requests disappear from routing logs?

A Service Worker may be handling them. Playwright recommends service_workers="block" when using request interception. If the application requires its Service Worker, treat that dependency as part of your test design; do not assume an absent route event means no work happened.

Why is the routed version slower even when it blocks images?

Routing disables the HTTP cache, and resource blocking can also affect page logic. Use the pass condition to separate those effects, then inspect errors and repeat the real navigation sequence. Increasing the wait time does not establish that the extraction is correct.

Can I use this to verify a screenshot workflow?

The supplied record comparison is insufficient for that task. Fonts, images and layout may be required outputs. Add visual acceptance criteria and permit the resources those criteria depend on before drawing a conclusion.

About the author

小羊 writes introductory explanations and practical tips about proxy IPs, application scenarios and common usage questions.

Expertise: Proxy IP fundamentals; application scenarios; common questions; introductory guides; practical usage tips.