Scrapy Playwright Proxy and Context Reuse
Find which layer applies a scrapy-playwright proxy and why reusing a named browser context can keep the old egress.
BotBrowser Team

Want the structured docs for Getting Started?
This article lives in the editorial library. For step-by-step setup, reference material, and ongoing updates, jump into the docs section.
A Request.meta["proxy"] value can look like the obvious place to change egress in a Scrapy spider, but it is not the supported proxy path when scrapy-playwright renders that request. The plugin requires proxy configuration on the Playwright browser or browser context, and an existing named context is reused with its original settings. BotBrowser can make the Chromium executable and profile explicit before the Playwright handler launches the browser. It does not create, recycle or re-proxy the plugin's named contexts. This page maps the ownership layers and provides an owned fixture contract for detecting stale context egress before a second page is fetched.
The distinction matters because Scrapy middleware, the scrapy-playwright download handler and Playwright browser contexts operate in different scopes. A middleware can rewrite a Scrapy request and still hand it to a handler whose browser object already has a proxy. A spider can send different playwright_context_kwargs and still land in an existing context if the name has not changed. The observable result is not a new proxy; it is a page fetched through the first context's network settings.
TL;DR
- scrapy-playwright documents that a proxy in the Scrapy
Request.meta["proxy"]key is not supported for Playwright downloads. - Proxy selection belongs to
PLAYWRIGHT_LAUNCH_OPTIONS,PLAYWRIGHT_CONTEXTS,playwright_context_kwargsat context creation, or the browser/provider configuration that creates the context. - Named contexts are cached by
playwright_context. A later request with the same name reuses that context and ignores new creation arguments. - Closing a page is not closing its browser context. Without an explicit context teardown, a long-lived named context can preserve its original proxy.
- To change egress, create a distinct context or close the existing context before retrying; then verify the context name, configured proxy and observed egress as separate record fields.
- BotBrowser can make the launched Chromium and profile declaration explicit; it does not own Scrapy's handler lifecycle or guarantee a proxy, page or site outcome.
Contents
- Three request boundaries
- Why request metadata is not the Playwright proxy switch
- Browser and context proxies have different scope
- A reused context keeps its creation-time egress
- How to change proxy without pretending reuse changed it
- Record egress as an application observation
- Where BotBrowser stops
- Practical conclusion
Three request boundaries
The first step is to identify which object receives the proxy instruction. Scrapy's downloader middleware chain processes a request before the selected download handler performs it. The scrapy-playwright handler then decides whether to use a browser page or the ordinary Scrapy download path. Once a page has been created, its context already owns the network configuration used by that page.
Those are three separate boundaries:
| Boundary | What it can decide | What it cannot prove |
|---|---|---|
| Scrapy request and middleware | URL, headers, scheduling state and routing to a handler | That a Playwright context uses a proxy from meta |
| scrapy-playwright handler | Which browser context and page serve a request; when a context is created or reused | That an unrelated middleware changed the browser proxy |
| Playwright browser / context | Network proxy for pages created in that browser or context | That the remote origin used the expected egress |
The downloader middleware documentation makes the first boundary explicit. A process_request hook may return None so the request continues to other middleware and eventually reaches the download handler. That means adding a value in middleware does not grant it execution semantics in a third-party handler. The handler has its own behavior.
The scrapy-playwright API adds a second condition: a request is rendered by Playwright only when request.meta["playwright"] is enabled. Without that marker, the handler delegates to its ordinary path. With it, the named context and page become the relevant browser objects. The Scrapy setup guide is useful for the broader boundary between Scrapy request processing and browser-controlled rendering; it does not define how a named Playwright context retains a proxy.
Why request metadata is not the Playwright proxy switch
Scrapy documents proxy and proxy_headers as request metadata for supported built-in download handlers. The same source warns that a third-party handler is not guaranteed to implement a metadata key from the built-in set. scrapy-playwright goes further in its own README: its known-issues section says per-request proxy support through the proxy request metadata key is not supported.
That is not a minor naming detail. A Scrapy request can be copied as it travels through redirects and callbacks, while a Playwright context is a longer-lived browser object. Attaching a different proxy string to a request does not rebuild the context around that request. The correct claim is therefore narrower and more useful:
Request.meta["proxy"]is Scrapy request state. It is not the scrapy-playwright mechanism that selects a Playwright context proxy.
The supported paths are shown in the plugin's proxy support section. PLAYWRIGHT_LAUNCH_OPTIONS can pass a browser-level proxy when the browser is launched. PLAYWRIGHT_CONTEXTS can precreate named contexts with their own context-level proxy. A request can create a new context with playwright_context_kwargs, including a proxy dictionary, but only if the named context does not already exist.
This is a more practical diagnosis than trying to patch the request after a page has loaded. If the observed egress is wrong, inspect the browser launch and the context object that produced the page. A proxy added solely to the Scrapy request may never have reached either one.
The Playwright proxy configuration guide covers the browser-protocol and launch side. The Scrapy integration adds another boundary: which layer receives the proxy, which layer remembers an existing context, and which layer supplies an observable egress record.
Browser and context proxies have different scope
Playwright supports a proxy on the browser launch and another on an individual browser context. Its network documentation says proxy settings can apply to the whole browser or to each context. The Browser.new_context API accepts a proxy object with fields such as server, username and password. A context proxy is a property of that object at creation time, not a property of each page navigation.
For scrapy-playwright, the documented settings divide the same way:
| Setting or metadata | Scope | Lifecycle that matters |
|---|---|---|
PLAYWRIGHT_LAUNCH_OPTIONS["proxy"] | The browser launched by the handler | Browser launch and browser-wide persistence |
PLAYWRIGHT_CONTEXTS[name]["proxy"] | A precreated context with that name | Context creation and lifetime |
playwright_context_kwargs["proxy"] | A context created on demand | First creation of that exact context name |
Request.meta["proxy"] | Scrapy request state for built-in handlers | Not a supported Playwright proxy path |
The table does not say that every proxy configuration has identical behavior across a local launch, CDP connection, remote Playwright connection or persistent context. The plugin documents distinct lifecycle branches for those modes. The table says what owns the setting: a browser object or a named context object, rather than a short-lived request field.
Context-level choice is useful when one spider needs clearly separated browser states. It is harmful when a context name is treated as a per-request selector. A name identifies a cached object. Repeating the same name is a request for reuse, not an instruction to rebuild the object with new arguments.
A reused context keeps its creation-time egress
The plugin creates the context through browser.new_context(**context_kwargs) when the requested name is absent, and stores the resulting wrapper by that name. On a later request with the same playwright_context, it gets the existing wrapper. The plugin's README describes the observable rule in one sentence: if a context with the specified name already exists, that context is used and playwright_context_kwargs are ignored.
The context also outlives the default page. When playwright_include_page is false, the handler closes the page after extracting the response. That page-close callback releases the page semaphore, but it does not remove the named context wrapper. The context remains available for the next page. This is the lifecycle that turns a proxy change into a silent no-op.
Consider a spider with an owned fixture that returns a stable egress_id. The fixture does not reveal a real proxy IP or make a third-party request; it records which local test origin answered the page. The proxy configuration is local and illustrative:
import scrapy
class ContextLifecycleSpider(scrapy.Spider):
name = "context-lifecycle"
async def start(self):
yield self.request_with_context(
"fixture-a",
"http://127.0.0.1:4100",
label="first",
)
yield self.request_with_context(
"fixture-a",
"http://127.0.0.1:4101",
label="same-name",
)
yield self.request_with_context(
"fixture-b",
"http://127.0.0.1:4101",
label="new-name",
)
def request_with_context(self, context_name, proxy_server, label):
return scrapy.Request(
"http://fixture.test/egress",
meta={
"playwright": True,
"playwright_context": context_name,
"playwright_context_kwargs": {
"proxy": {"server": proxy_server},
},
"trace_label": label,
},
callback=self.parse_egress,
)
def parse_egress(self, response, **kwargs):
yield {
"label": response.meta["trace_label"],
"context": response.meta["playwright_context"],
"egress": response.json()["egress_id"],
}
The expected records, not captured runtime output, are:
| Label | Context name | Requested proxy | Expected egress | Why |
|---|---|---|---|---|
first | fixture-a | :4100 | A | The first request creates fixture-a |
same-name | fixture-a | :4101 | A | The existing context is reused; new kwargs are ignored |
new-name | fixture-b | :4101 | B | A distinct name causes a new context to be created |
This small example is more useful than a generic retry because it reveals the exact ownership mistake. If the second row returns B, the tested handler created a new context despite the same name, or the fixture did not model context creation as claimed. If the second row returns an error, separate a proxy connection error from a context reuse claim. If it returns A, the expected behavior is consistent with context reuse. The fixture cannot establish a third-party site's response or a public proxy's real location.
The plugin source reinforces why a page close is insufficient. A page-close callback releases a page semaphore; a browser-context-close callback removes the named wrapper. Those are different events. Waiting for the page to complete does not reset the context's proxy. A retry that reuses the same context therefore usually retries through the same context.
How to change proxy without pretending reuse changed it
There are two bounded ways to make the next browser navigation use a different context configuration. The first is to give the new policy a distinct context name. The second is to explicitly close the old context before asking scrapy-playwright to create a new one with the same name. Both should be followed by a fresh egress observation rather than an assumption that a setting changed.
The named separation is easiest to reason about:
yield scrapy.Request(
"http://fixture.test/egress",
meta={
"playwright": True,
"playwright_context": "egress-b",
"playwright_context_kwargs": {
"proxy": {"server": "http://127.0.0.1:4101"},
},
},
)
If the spider needs to retain the page object to close its context in a callback, enable playwright_include_page and explicitly await page.context.close(). Do not infer that closing a page changed the named context. Keep an errback path that closes the context when the main callback fails, and do not continue to reuse the old name until the close event has completed.
def parse_with_owned_page(self, response, **kwargs):
page = response.meta["playwright_page"]
context = page.context
try:
yield {"egress": response.json()["egress_id"]}
finally:
yield scrapy.Request(
"http://fixture.test/close-context",
meta={"playwright": True, "playwright_context": "cleanup"},
dont_filter=True,
callback=lambda _: None,
)
Treat that second snippet as a shape for the cleanup handoff, not a complete async teardown implementation. In real code, await the context close on the Playwright object and handle a close error explicitly. The application should record whether it observed the old context close before it requested a new one. A command that merely closes an HTML page or starts a new Scrapy request is not that evidence.
The plugin's persistent-context branch adds another boundary: a context launched with user_data_dir is persistent and is launched independently from the main browser instance. Do not fold persistent contexts, ordinary contexts and contexts attached through a remote connection into one lifecycle statement. The safe design rule is still the same: record the exact object and its creation settings; use a new name or a completed close when the egress policy changes.
The BotBrowser launcher proxy verification supplies a useful example of verifying an egress outcome with an owned endpoint. A preparation retry still needs that response evidence: a context can be misconfigured and a retry can still hit the old proxy. The contract is a response, not an inference from configuration.
Record egress as an application observation
A useful troubleshooting record has three types of facts: intended configuration, the selected Playwright context and the result the application could actually observe. Keep them separate. PLAYWRIGHT_LAUNCH_OPTIONS or playwright_context_kwargs prove what the spider asked the handler to create. The context name proves which browser object scope the request intended to use. A bounded fixture response proves only what that fixture returned.
| Record field | Illustration | What it establishes |
|---|---|---|
| Intended policy | proxy=A, context=fixture-a | The spider's requested context and proxy settings |
| Handler path | meta.playwright=true | This request is eligible for Playwright rendering |
| Context identity | playwright_context=fixture-a | The named scope the request will reuse |
| Observed egress | egress_id=A from an owned fixture | The fixture saw a response associated with egress A |
| Context teardown | context.close() completed before retry | The named wrapper can be recreated, if confirmed |
| Origin outcome | HTTP 503 or HTTP 200 from the fixture | The fixture's response, not a site's acceptance claim |
Avoid recording a proxy password, full request headers or a third-party page body in a routine diagnostic. A redacted proxy label and a local fixture response are enough to identify the layer. If the observed egress differs from the intended setting, route the finding to the first unsupported layer: request metadata, handler creation, context reuse or actual network connectivity. Do not call it “Scrapy changed the proxy” when only a request object changed.
The same logic helps separate failures that look alike. A request with playwright absent uses the ordinary handler and may obey Scrapy metadata differently. A request with a new context name but an invalid proxy cannot establish a context-reuse bug. A request that reuses a valid context after changing its kwargs can establish reuse when its egress remains the original one. A closed context that is recreated later needs a new creation observation, not the old context's record.
Where BotBrowser stops
BotBrowser's Playwright setup documents an explicit executable and --bot-profile launch input. That gives an application a declared browser environment before the Scrapy handler creates its browser and contexts. It does not define a replacement for scrapy-playwright proxy selection, and it does not inspect the plugin's context cache.
For a deterministic run, the application can record the BotBrowser launch input, the scrapy-playwright handler configuration, the selected context name and the owned fixture's egress response. It can then decide whether each fact belongs to the executable boundary, the handler boundary or the context boundary. A profile that was loaded successfully does not prove a page used the intended proxy, and a proxy configured at the browser does not prove the page's application-level action succeeded.
The supported rule is intentionally conservative: use the plugin's browser or context proxy configuration, make context lifetime visible, and verify the outcome with an owned page. Avoid treating a profile, a proxy URL, a Scrapy Request.meta field or a page-close call as interchangeable proof.
FAQ
Does request.meta["proxy"] change the proxy for a scrapy-playwright request?
No. scrapy-playwright's documented known issue says the proxy request metadata key is not supported for its Playwright path. Configure the browser or named context proxy instead, and verify the resulting egress separately.
Why does a second request ignore the new proxy in playwright_context_kwargs?
The context name already maps to a cached browser context. The plugin reuses that context and ignores creation kwargs for the existing object. Use a new context name or close the old context before requiring a new creation.
Is closing the page enough to reset the browser context?
No. A page and a browser context are different objects. Closing a page does not remove its context, and the plugin's named context can remain available. Explicitly close the context if the next request needs a new context object, then wait for that close before retrying.
Can BotBrowser make a scrapy-playwright context use a different proxy?
BotBrowser can make the Chromium executable and profile declaration explicit, but it does not manage scrapy-playwright context creation or Scrapy retry policy. Proxy selection still belongs to the supported browser or context configuration path.
Sources
- scrapy-playwright repository
- scrapy-playwright on PyPI
- Scrapy downloader middleware
- Scrapy Request.meta and proxy metadata
- Playwright Python network and HTTP proxy
- Playwright Browser.new_context
- BotBrowser Playwright setup
Practical conclusion
When a scrapy-playwright request uses the wrong egress, identify the browser or context that created the page before changing request metadata. Request.meta["proxy"] belongs to Scrapy's request model, not to a supported scrapy-playwright proxy path. Named contexts are cached, and a reused context keeps the proxy it received when it was created. Record the intended proxy, the context name and an owned fixture's observed egress; change proxy policy with a distinct context or an explicit closed context, then verify the next response. BotBrowser can make the browser executable and profile explicit, but it does not decide whether scrapy-playwright reused an old context.
This article is part of the guide: Browser Automation Getting Started: A First Run Map
Related Articles
Scrapy browser fingerprint: What Scrapy Cannot Set
Getting StartedPlaywright Clear Cookies Versus a New Context: What Each Reset Removes
Getting StartedPlaywright Proxy: Routing, Auth and Unchanged Signals
NetworkPuppeteer Proxy: Configure It and Verify the Exit
Getting StartedProxy Launcher in BotBrowser: Profiles, Proxies, and Setup
Getting StartedPlaywright executablePath: Which Browser Actually Runs
Run the same check in BotBrowser
Load a profile, keep the signals you just read about consistent inside the browser, and confirm the result on your own machine before a rollout.