Network
Playwright provides APIs to monitor and modify network traffic, both HTTP and HTTPS. Any requests that a page does, including XHRs and fetch requests, can be tracked, modified and handled.
HTTP Authentication
Perform HTTP Authentication.
- Sync
- Async
context = browser.new_context(
http_credentials={"username": "bill", "password": "pa55w0rd"}
)
page = context.new_page()
page.goto("https://example.com")
context = await browser.new_context(
http_credentials={"username": "bill", "password": "pa55w0rd"}
)
page = await context.new_page()
await page.goto("https://example.com")
HTTP Proxy
You can configure pages to load over the HTTP(S) proxy or SOCKSv5. Proxy can be either set globally for the entire browser, or for each browser context individually.
You can optionally specify username and password for HTTP(S) proxy, you can also specify hosts to bypass proxy for.
Here is an example of a global proxy:
- Sync
- Async
browser = chromium.launch(proxy={
"server": "http://myproxy.com:3128",
"username": "usr",
"password": "pwd"
})
browser = await chromium.launch(proxy={
"server": "http://myproxy.com:3128",
"username": "usr",
"password": "pwd"
})
When specifying proxy for each context individually, Chromium on Windows needs a hint that proxy will be set. This is done via passing a non-empty proxy server to the browser itself. Here is an example of a context-specific proxy:
- Sync
- Async
# Browser proxy option is required for Chromium on Windows.
browser = chromium.launch(proxy={"server": "per-context"})
context = browser.new_context(proxy={"server": "http://myproxy.com:3128"})
# Browser proxy option is required for Chromium on Windows.
browser = await chromium.launch(proxy={"server": "per-context"})
context = await browser.new_context(proxy={"server": "http://myproxy.com:3128"})
Network events
You can monitor all the Requests and Responses:
- Sync
- Async
from playwright.sync_api import sync_playwright
def run(playwright):
chromium = playwright.chromium
browser = chromium.launch()
page = browser.new_page()
# Subscribe to "request" and "response" events.
page.on("request", lambda request: print(">>", request.method, request.url))
page.on("response", lambda response: print("<<", response.status, response.url))
page.goto("https://example.com")
browser.close()
with sync_playwright() as playwright:
run(playwright)
import asyncio
from playwright.async_api import async_playwright
async def run(playwright):
chromium = playwright.chromium
browser = await chromium.launch()
page = await browser.new_page()
# Subscribe to "request" and "response" events.
page.on("request", lambda request: print(">>", request.method, request.url))
page.on("response", lambda response: print("<<", response.status, response.url))
await page.goto("https://example.com")
await browser.close()
async def main():
async with async_playwright() as playwright:
await run(playwright)
asyncio.run(main())
Or wait for a network response after the button click with page.expect_response():
- Sync
- Async
# Use a glob url pattern
with page.expect_response("**/api/fetch_data") as response_info:
page.get_by_text("Update").click()
response = response_info.value
# Use a glob url pattern
async with page.expect_response("**/api/fetch_data") as response_info:
await page.get_by_text("Update").click()
response = await response_info.value
Variations
Wait for Responses with page.expect_response()
- Sync
- Async
# Use a regular expression
with page.expect_response(re.compile(r"\.jpeg$")) as response_info:
page.get_by_text("Update").click()
response = response_info.value
# Use a predicate taking a response object
with page.expect_response(lambda response: token in response.url) as response_info:
page.get_by_text("Update").click()
response = response_info.value
# Use a regular expression
async with page.expect_response(re.compile(r"\.jpeg$")) as response_info:
await page.get_by_text("Update").click()
response = await response_info.value
# Use a predicate taking a response object
async with page.expect_response(lambda response: token in response.url) as response_info:
await page.get_by_text("Update").click()
response = await response_info.value
Handle requests
- Sync
- Async
page.route(
"**/api/fetch_data",
lambda route: route.fulfill(status=200, body=test_data))
page.goto("https://example.com")
await page.route(
"**/api/fetch_data",
lambda route: route.fulfill(status=200, body=test_data))
await page.goto("https://example.com")
You can mock API endpoints via handling the network requests in your Playwright script.
Variations
Set up route on the entire browser context with browser_context.route() or page with page.route(). It will apply to popup windows and opened links.
- Sync
- Async
context.route(
"**/api/login",
lambda route: route.fulfill(status=200, body="accept"))
page.goto("https://example.com")
await context.route(
"**/api/login",
lambda route: route.fulfill(status=200, body="accept"))
await page.goto("https://example.com")
Modify requests
- Sync
- Async
# Delete header
def handle_route(route):
headers = route.request.headers
del headers["x-secret"]
route.continue_(headers=headers)
page.route("**/*", handle_route)
# Continue requests as POST.
page.route("**/*", lambda route: route.continue_(method="POST"))
# Delete header
async def handle_route(route):
headers = route.request.headers
del headers["x-secret"]
route.continue_(headers=headers)
await page.route("**/*", handle_route)
# Continue requests as POST.
await page.route("**/*", lambda route: route.continue_(method="POST"))
You can continue requests with modifications. Example above removes an HTTP header from the outgoing requests.
Abort requests
You can abort requests using page.route() and route.abort().
- Sync
- Async
page.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
# Abort based on the request type
page.route("**/*", lambda route: route.abort() if route.request.resource_type == "image" else route.continue_())
await page.route("**/*.{png,jpg,jpeg}", lambda route: route.abort())
# Abort based on the request type
await page.route("**/*", lambda route: route.abort() if route.request.resource_type == "image" else route.continue_())
Modify responses
To modify a response use APIRequestContext to get the original response and then pass the response to route.fulfill(). You can override individual fields on the response via options:
- Sync
- Async
def handle_route(route: Route) -> None:
# Fetch original response.
response = route.fetch()
# Add a prefix to the title.
body = response.text()
body = body.replace("<title>", "<title>My prefix:")
route.fulfill(
# Pass all fields from the response.
response=response,
# Override response body.
body=body,
# Force content type to be html.
headers={**response.headers, "content-type": "text/html"},
)
page.route("**/title.html", handle_route)
async def handle_route(route: Route) -> None:
# Fetch original response.
response = await route.fetch()
# Add a prefix to the title.
body = await response.text()
body = body.replace("<title>", "<title>My prefix:")
await route.fulfill(
# Pass all fields from the response.
response=response,
# Override response body.
body=body,
# Force content type to be html.
headers={**response.headers, "content-type": "text/html"},
)
await page.route("**/title.html", handle_route)
Record and replay requests
You can record network activity as an HTTP Archive file (HAR). Later on, this archive can be used to mock responses to the network requests. You'll need to:
- Record a HAR file.
- Commit the HAR file alongside the tests.
- Route requests using the saved HAR files in the tests.
Recording HAR with CLI
Open the browser with Playwright CLI and pass --save-har
option to produce a HAR file. Optionally, use --save-har-glob
to only save requests you are interested in, for example API endpoints. If the har file name ends with .zip
, artifacts are written as separate files and are all compressed into a single zip
.
# Save API requests from example.com as "example.har" archive.
playwright open --save-har=example.har --save-har-glob="**/api/**" https://example.coms
Recording HAR with a script
Alternatively, instead of using the CLI, you can record HAR programmatically. Pass har
option when creating a BrowserContext with browser.new_context() to create an archive. If the har file name ends with .zip
, artifacts are written as separate files and are all compressed into a single zip
.
- Sync
- Async
context = browser.new_context(record_har_path="example.har", record_har_url_filter="**/api/**")
# ... Perform actions ...
# Close context to ensure HAR is saved to disk.
context.close()
context = await browser.new_context(record_har_path="example.har", record_har_url_filter="**/api/**")
# ... Perform actions ...
# Close context to ensure HAR is saved to disk.
await context.close()
Replaying from HAR
Use page.route_from_har() or browser_context.route_from_har() to serve matching responses from the HAR file.
- Sync
- Async
# Either use a matching response from the HAR,
# or abort the request if nothing matches.
page.route_from_har("example.har")
# Either use a matching response from the HAR,
# or abort the request if nothing matches.
await page.route_from_har("example.har")
HAR replay matches URL and HTTP method strictly. For POST requests, it also matches POST payloads strictly. If multiple recordings match a request, the one with the most matching headers is picked. An entry resulting in a redirect will be followed automatically.
Similar to when recording, if given HAR file name ends with .zip
, it is considered an archive containing the HAR file along with network payloads stored as separate entries. You can also extract this archive, edit payloads or HAR log manually and point to the extracted har file. All the payloads will be resolved relative to the extracted har file on the file system.
WebSockets
Playwright supports WebSockets inspection out of the box. Every time a WebSocket is created, the page.on("websocket") event is fired. This event contains the WebSocket instance for further web socket frames inspection:
def on_web_socket(ws):
print(f"WebSocket opened: {ws.url}")
ws.on("framesent", lambda payload: print(payload))
ws.on("framereceived", lambda payload: print(payload))
ws.on("close", lambda payload: print("WebSocket closed"))
page.on("websocket", on_web_socket)
Missing Network Events and Service Workers
Playwright's built-in browser_context.route() and page.route() allow your tests to natively route requests and perform mocking and interception.
- If you're using Playwright's native browser_context.route() and page.route(), and it appears network events are missing, disable Service Workers by setting
browser.new_context.service_workers
to'block'
. - It might be that you are using a mock tool such as Mock Service Worker (MSW). While this tool works out of the box for mocking responses, it adds its own Service Worker that takes over the network requests, hence making them invisible to browser_context.route() and page.route(). If you are interested in both network testing and mocking, consider using built-in browser_context.route() and page.route() for response mocking.
- If you're interested in not solely using Service Workers for testing and network mocking, but in routing and listening for requests made by Service Workers themselves, please see this experimental feature.