### Install Browser and System Dependencies Together Source: https://playwright.dev/python/docs/browsers Combine browser installation with system dependency installation using a single command. Simplifies setup, especially for specific browsers like Chromium. ```bash playwright install --with-deps chromium ``` -------------------------------- ### Enable Animations and Control Playback (Sync) Source: https://playwright.dev/python/docs/api/class-cdpsession Use this synchronous example to enable the Animation domain, subscribe to animation creation events, and then get and set the animation playback rate. ```python client = page.context.new_cdp_session(page) client.send("Animation.enable") client.on("Animation.animationCreated", lambda: print("animation created!")) response = client.send("Animation.getPlaybackRate") print("playback rate is " + str(response["playbackRate"])) client.send("Animation.setPlaybackRate", { "playbackRate": response["playbackRate"] / 2 }) ``` -------------------------------- ### Create Page, Navigate, and Screenshot (Async) Source: https://playwright.dev/python/docs/api/class-page This asynchronous example demonstrates launching a WebKit browser, creating a new page, navigating to a URL, and saving a screenshot using `asyncio`. Ensure Playwright is installed. ```python import asyncio from playwright.async_api import async_playwright, Playwright async def run(playwright: Playwright): webkit = playwright.webkit browser = await webkit.launch() context = await browser.new_context() page = await context.new_page() await page.goto("https://example.com") await page.screenshot(path="screenshot.png") await browser.close() async def main(): async with async_playwright() as playwright: await run(playwright) asyncio.run(main()) ``` -------------------------------- ### Create Page, Navigate, and Screenshot (Sync) Source: https://playwright.dev/python/docs/api/class-page Use this synchronous example to launch a WebKit browser, create a new page, navigate to a URL, and save a screenshot. Ensure Playwright is installed. ```python from playwright.sync_api import sync_playwright, Playwright def run(playwright: Playwright): webkit = playwright.webkit browser = webkit.launch() context = browser.new_context() page = context.new_page() page.goto("https://example.com") page.screenshot(path="screenshot.png") browser.close() with sync_playwright() as playwright: run(playwright) ``` -------------------------------- ### List Supported Browsers for Installation Source: https://playwright.dev/python/docs/browsers View all available browsers that can be installed using the Playwright CLI. Useful for understanding installation options. ```bash playwright install --help ``` -------------------------------- ### Start Tracing with Options (Async) Source: https://playwright.dev/python/docs/api/class-tracing Starts tracing asynchronously with options for screenshots, snapshots, and source files. The trace is saved to a zip file. ```python await context.tracing.start(screenshots=True, snapshots=True) page = await context.new_page() await page.goto("https://playwright.dev") await context.tracing.stop(path = "trace.zip") ``` -------------------------------- ### Start Tracing with Options (Sync) Source: https://playwright.dev/python/docs/api/class-tracing Starts tracing with options for screenshots, snapshots, and source files. The trace is saved to a zip file. ```python context.tracing.start(screenshots=True, snapshots=True) page = context.new_page() page.goto("https://playwright.dev") context.tracing.stop(path = "trace.zip") ``` -------------------------------- ### Asynchronous APIResponse Example Source: https://playwright.dev/python/docs/api/class-apiresponse Demonstrates how to make an asynchronous GET request and assert properties of the APIResponse. ```python import asyncio from playwright.async_api import async_playwright, Playwright async def run(playwright: Playwright): context = await playwright.request.new_context() response = await context.get("https://example.com/user/repos") assert response.ok assert response.status == 200 assert response.headers["content-type"] == "application/json; charset=utf-8" json_data = await response.json() assert json_data["name"] == "foobar" assert await response.body() == '{"status": "ok"}' async def main(): async with async_playwright() as playwright: await run(playwright) asyncio.run(main()) ``` -------------------------------- ### Record with Custom Sync Setup Source: https://playwright.dev/python/docs/codegen Use this synchronous Python snippet to start codegen recording with a custom browser context. Ensure the browser is launched in headed mode. The `context.route` is set up to continue all requests. ```python from playwright.sync_api import sync_playwright with sync_playwright() as p: # Make sure to run headed. browser = p.chromium.launch(headless=False) # Setup context however you like. context = browser.new_context() # Pass any options context.route('**/*', lambda route: route.continue_()) # Pause the page, and start recording manually. page = context.new_page() page.pause() ``` -------------------------------- ### Synchronous APIResponse Example Source: https://playwright.dev/python/docs/api/class-apiresponse Demonstrates how to make a GET request and assert properties of the synchronous APIResponse. ```python from playwright.sync_api import sync_playwright with sync_playwright() as p: context = playwright.request.new_context() response = context.get("https://example.com/user/repos") assert response.ok assert response.status == 200 assert response.headers["content-type"] == "application/json; charset=utf-8" assert response.json()["name"] == "foobar" assert response.body() == '{"status": "ok"}' ``` -------------------------------- ### Install and Manage Timers with Playwright Clock (Python) Source: https://playwright.dev/python/docs/clock Use `page.clock.install` to initialize the clock with a starting time. `pause_at` stops time progression at a specific point, and `fast_forward` advances time by a duration. This is useful when timers depend on `Date.now` and need to be controlled. ```python # Initialize clock with some time before the test time and let the page load # naturally. `Date.now` will progress as the timers fire. page.clock.install(time=datetime.datetime(2024, 2, 2, 8, 0, 0)) page.goto("http://localhost:3333") # Pretend that the user closed the laptop lid and opened it again at 10am. # Pause the time once reached that point. page.clock.pause_at(datetime.datetime(2024, 2, 2, 10, 0, 0)) # Assert the page state. expect(page.get_by_test_id("current-time")).to_have_text("2/2/2024, 10:00:00 AM") # Close the laptop lid again and open it at 10:30am. page.clock.fast_forward("30:00") expect(page.get_by_test_id("current-time")).to_have_text("2/2/2024, 10:30:00 AM") ``` -------------------------------- ### Record with Custom Async Setup Source: https://playwright.dev/python/docs/codegen This asynchronous Python snippet shows how to initiate codegen recording with a custom browser context. It requires running the browser in headed mode and setting up context routes. The `page.pause()` function is used to manually start recording. ```python import asyncio from playwright.async_api import async_playwright async def main(): async with async_playwright() as p: # Make sure to run headed. browser = await p.chromium.launch(headless=False) # Setup context however you like. context = await browser.new_context() # Pass any options await context.route('**/*', lambda route: route.continue_()) # Pause the page, and start recording manually. page = await context.new_page() await page.pause() asyncio.run(main()) ``` -------------------------------- ### start Source: https://playwright.dev/python/docs/api/class-screencast Starts the screencast. When path is provided, it saves video recording to the specified file. When on_frame is provided, delivers JPEG-encoded frames to the callback. Both can be used together. ```APIDOC ## start ### Description Starts the screencast. When path is provided, it saves video recording to the specified file. When on_frame is provided, delivers JPEG-encoded frames to the callback. Both can be used together. ### Method POST ### Endpoint /screencast/start ### Parameters #### Query Parameters - **on_frame** (Callable) - Optional - Callback that receives JPEG-encoded frame data along with the page viewport size at the time of capture. The callback receives `data` (bytes), `timestamp` (float), `viewportWidth` (int), and `viewportHeight` (int). - **path** (string | pathlib.Path) - Optional - Path where the video should be saved when the screencast is stopped. - **quality** (int) - Optional - The quality of the image, between 0-100. - **size** (Dict) - Optional - Specifies the dimensions of screencast frames. The actual frame is scaled to preserve the page's aspect ratio and may be smaller than these bounds. It has `width` (int) and `height` (int) properties. ### Returns * Disposable ``` -------------------------------- ### Install Playwright Browsers Source: https://playwright.dev/python/docs/intro Run this command to download and install the necessary browsers for Playwright to use. ```bash playwright install ``` -------------------------------- ### Install Playwright with uv Source: https://playwright.dev/python/docs/library Installs the Playwright package and its browser binaries using uv. ```bash uv self update uv add playwright playwright install ``` -------------------------------- ### Install and Pause Clock for Page Load Source: https://playwright.dev/python/docs/api/class-clock Install the clock with an initial time before navigating, then use `pause_at` after the page loads. This ensures timers behave normally during loading and allows precise control afterward. ```python # Initialize clock with some time before the test time and let the page load # naturally. `Date.now` will progress as the timers fire. page.clock.install(time=datetime.datetime(2024, 12, 10, 8, 0, 0)) page.goto("http://localhost:3333") page.clock.pause_at(datetime.datetime(2024, 12, 10, 10, 0, 0)) ``` ```python # Initialize clock with some time before the test time and let the page load # naturally. `Date.now` will progress as the timers fire. await page.clock.install(time=datetime.datetime(2024, 12, 10, 8, 0, 0)) await page.goto("http://localhost:3333") await page.clock.pause_at(datetime.datetime(2024, 12, 10, 10, 0, 0)) ``` -------------------------------- ### Install Default Playwright Browsers Source: https://playwright.dev/python/docs/browsers Run this command to install the default set of browsers supported by Playwright. This is the most common installation command. ```bash playwright install ``` -------------------------------- ### Install Microsoft Edge using Playwright CLI Source: https://playwright.dev/python/docs/browsers Install Microsoft Edge or Google Chrome using the Playwright command-line tool with the `playwright install` command followed by the browser name. ```bash playwright install msedge ``` -------------------------------- ### Complete API Test Example Source: https://playwright.dev/python/docs/api-testing This snippet demonstrates a full API test setup using Playwright. It includes fixtures for API request context, repository creation, and teardown. It also contains two test functions for creating bug reports and feature requests. ```python from enum import auto import os from typing import Generator import pytest from playwright.sync_api import Playwright, Page, APIRequestContext, expect GITHUB_API_TOKEN = os.getenv("GITHUB_API_TOKEN") assert GITHUB_API_TOKEN, "GITHUB_API_TOKEN is not set" GITHUB_USER = os.getenv("GITHUB_USER") assert GITHUB_USER, "GITHUB_USER is not set" GITHUB_REPO = "test" @pytest.pytest.fixture(scope="session") def api_request_context( playwright: Playwright, ) -> Generator[APIRequestContext, None, None]: headers = { # We set this header per GitHub guidelines. "Accept": "application/vnd.github.v3+json", # Add authorization token to all requests. # Assuming personal access token available in the environment. "Authorization": f"token {GITHUB_API_TOKEN}", } request_context = playwright.request.new_context( base_url="https://api.github.com", extra_http_headers=headers ) yield request_context request_context.dispose() @pytest.pytest.fixture(scope="session", autouse=True) def create_test_repository( api_request_context: APIRequestContext, ) -> Generator[None, None, None]: # Before all new_repo = api_request_context.post("/user/repos", data={"name": GITHUB_REPO}) assert new_repo.ok yield # After all deleted_repo = api_request_context.delete(f"/repos/{GITHUB_USER}/{GITHUB_REPO}") assert deleted_repo.ok def test_should_create_bug_report(api_request_context: APIRequestContext) -> None: data = { "title": "[Bug] report 1", "body": "Bug description", } new_issue = api_request_context.post( f"/repos/{GITHUB_USER}/{GITHUB_REPO}/issues", data=data ) assert new_issue.ok issues = api_request_context.get(f"/repos/{GITHUB_USER}/{GITHUB_REPO}/issues") assert issues.ok issues_response = issues.json() issue = list( filter(lambda issue: issue["title"] == "[Bug] report 1", issues_response) )[0] assert issue assert issue["body"] == "Bug description" def test_should_create_feature_request(api_request_context: APIRequestContext) -> None: data = { "title": "[Feature] request 1", "body": "Feature description", } new_issue = api_request_context.post( f"/repos/{GITHUB_USER}/{GITHUB_REPO}/issues", data=data ) assert new_issue.ok issues = api_request_context.get(f"/repos/{GITHUB_USER}/{GITHUB_REPO}/issues") assert issues.ok issues_response = issues.json() issue = list( filter(lambda issue: issue["title"] == "[Feature] request 1", issues_response) )[0] assert issue assert issue["body"] == "Feature description" ``` -------------------------------- ### Install WebAuthn Authenticator Source: https://playwright.dev/python/docs/api/class-credentials Installs the virtual WebAuthn authenticator. Call this before the page interacts with navigator.credentials. ```python credentials.install() ``` -------------------------------- ### Install Edge on Linux Source: https://playwright.dev/python/docs/release-notes Use the npx playwright install command with the 'msedge' argument to install the stable version of Microsoft Edge on Linux systems. ```bash npx playwright install msedge ``` -------------------------------- ### Start Screencast Recording Source: https://playwright.dev/python/docs/api/class-screencast Starts the screencast. Can save video to a file path, deliver JPEG-encoded frames to a callback, or both. Options include frame quality and size constraints. If a screencast is already active, the existing configuration takes precedence. ```python screencast.start() ``` -------------------------------- ### Install Playwright and Dependencies Source: https://playwright.dev/python/docs/ci Use these commands to install Playwright and its browser dependencies. The `playwright install --with-deps` command ensures all necessary system dependencies are also installed. ```bash pip install playwright ``` ```bash playwright install --with-deps ``` -------------------------------- ### Install Playwright with Poetry Source: https://playwright.dev/python/docs/library Installs the Playwright package and its browser binaries using Poetry. ```bash poetry self update poetry add playwright playwright install ``` -------------------------------- ### Install Playwright and Specify Browser Path (Bash) Source: https://playwright.dev/python/docs/browsers Install Playwright and instruct it to download browsers into a custom directory using the PLAYWRIGHT_BROWSERS_PATH environment variable in Bash. ```bash pip install playwright PLAYWRIGHT_BROWSERS_PATH=$HOME/pw-browsers python -m playwright install ``` -------------------------------- ### Install Clock Emulation Source: https://playwright.dev/python/docs/api/class-clock Use `install()` to replace native time-related functions with fakes. This allows manual control over time flow in tests. Call this before navigating to ensure all timers function correctly during page load. ```python clock.install() clock.install(**kwargs) ``` -------------------------------- ### Configure Custom Download Host (Batch) Source: https://playwright.dev/python/docs/browsers Use the set command to define PLAYWRIGHT_DOWNLOAD_HOST for custom browser binary locations. Install Playwright first, then execute the install command. ```batch set PLAYWRIGHT_DOWNLOAD_HOST=http://192.0.2.1 pip install playwright playwright install ``` -------------------------------- ### Install Playwright and Specify Browser Path (Batch) Source: https://playwright.dev/python/docs/browsers Install Playwright and instruct it to download browsers into a custom directory using the PLAYWRIGHT_BROWSERS_PATH environment variable in a Batch file. ```batch set PLAYWRIGHT_BROWSERS_PATH=%USERPROFILE%\pw-browsers pip install playwright playwright install ``` -------------------------------- ### Install System Dependencies for Playwright Source: https://playwright.dev/python/docs/browsers Automatically install necessary system dependencies for Playwright. Recommended for CI environments to ensure Playwright runs correctly. ```bash playwright install-deps ``` -------------------------------- ### install Source: https://playwright.dev/python/docs/clock Initializes the clock and provides methods to pause, fast forward, run for a duration, or resume time. ```APIDOC ## install ### Description Initializes the clock and allows for advanced time manipulation such as pausing, fast forwarding, and running for specific durations. ### Method APIDOC ### Endpoint APIDOC ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json {} ``` ### Response #### Success Response (200) No specific response body documented. ### Sub-methods available after install: #### pauseAt ##### Description Pauses the time at a specific time. ##### Parameters - **time** (number) - Required - The timestamp in milliseconds to pause at. #### fastForward ##### Description Fast forwards the time. ##### Parameters - **duration** (number) - Required - The duration in milliseconds to fast forward. #### runFor ##### Description Runs the time for a specific duration. ##### Parameters - **duration** (number) - Required - The duration in milliseconds to run for. #### resume ##### Description Resumes the normal flow of time. ``` -------------------------------- ### Get Browser Name Source: https://playwright.dev/python/docs/api/class-browsertype Retrieve the name of the browser. For example: 'chromium', 'webkit', or 'firefox'. ```python browser_type.name ``` -------------------------------- ### Get path to downloaded file Source: https://playwright.dev/python/docs/api/class-download Use `download.path()` to get the `pathlib.Path` object for the downloaded file. This method waits for the download to complete and throws an error for failed or canceled downloads. Note that the actual file name is a GUID; use `suggested_filename` for the user-friendly name. ```python download.path() ``` -------------------------------- ### Install Dependencies via Proxy on Linux (Root) Source: https://playwright.dev/python/docs/browsers When installing dependencies on Linux with a proxy, use sudo to ensure environment variables like HTTPS_PROXY are passed correctly to the package manager. ```bash sudo HTTPS_PROXY=https://192.0.2.1 playwright install-deps ``` -------------------------------- ### Start and Stop Trace Chunks (Async) Source: https://playwright.dev/python/docs/api/class-tracing Demonstrates how to start and stop multiple trace chunks within a single tracing session using asynchronous API calls. This is useful for recording distinct sets of actions in separate trace files. ```python await context.tracing.start(screenshots=True, snapshots=True) page = await context.new_page() await page.goto("https://playwright.dev") await context.tracing.start_chunk() await page.get_by_text("Get Started").click() # Everything between start_chunk and stop_chunk will be recorded in the trace. await context.tracing.stop_chunk(path = "trace1.zip") await context.tracing.start_chunk() await page.goto("http://example.com") # Save a second trace file with different actions. await context.tracing.stop_chunk(path = "trace2.zip") ``` -------------------------------- ### Start and Stop Trace Chunks (Sync) Source: https://playwright.dev/python/docs/api/class-tracing Demonstrates how to start and stop multiple trace chunks within a single tracing session using synchronous API calls. This is useful for recording distinct sets of actions in separate trace files. ```python context.tracing.start(screenshots=True, snapshots=True) page = context.new_page() page.goto("https://playwright.dev") context.tracing.start_chunk() page.get_by_text("Get Started").click() # Everything between start_chunk and stop_chunk will be recorded in the trace. context.tracing.stop_chunk(path = "trace1.zip") context.tracing.start_chunk() page.goto("http://example.com") # Save a second trace file with different actions. context.tracing.stop_chunk(path = "trace2.zip") ``` -------------------------------- ### Run Playwright Server in Docker Source: https://playwright.dev/python/docs/docker Start the Playwright Server within a Docker container, mapping the server port to the host. This setup is useful for remote execution or running tests on unsupported environments. ```docker docker run -p 3000:3000 --rm --init -it --workdir /home/pwuser --user pwuser mcr.microsoft.com/playwright:v1.60.0-noble /bin/sh -c "npx -y playwright@1.60.0 run-server --port 3000 --host 0.0.0.0" ``` -------------------------------- ### Emulate Color Scheme and Media (Async) Source: https://playwright.dev/python/docs/emulation Demonstrates creating a context and page with a specific color scheme ('dark' or 'light'), and emulating media types like 'print' asynchronously. Use `emulate_media` to change settings for existing pages. ```python # Create context with dark mode context = await browser.new_context( color_scheme='dark' # or 'light' ) # Create page with dark mode page = await browser.new_page( color_scheme='dark' # or 'light' ) # Change color scheme for the page await page.emulate_media(color_scheme='dark') # Change media for page await page.emulate_media(media='print') ``` -------------------------------- ### Get Resource Timing Information for a Request (Sync) Source: https://playwright.dev/python/docs/api/class-request Fetch resource timing details for a request. Timing information becomes available upon receiving the response, with `responseEnd` populated when the request completes. This example demonstrates synchronous event handling. ```python with page.expect_event("requestfinished") as request_info: page.goto("http://example.com") request = request_info.value print(request.timing) ``` -------------------------------- ### Enable Animations and Control Playback (Async) Source: https://playwright.dev/python/docs/api/class-cdpsession This asynchronous example demonstrates enabling the Animation domain, subscribing to animation creation events, and then retrieving and modifying the animation playback rate. ```python client = await page.context.new_cdp_session(page) await client.send("Animation.enable") client.on("Animation.animationCreated", lambda: print("animation created!")) response = await client.send("Animation.getPlaybackRate") print("playback rate is " + str(response["playbackRate"])) await client.send("Animation.setPlaybackRate", { "playbackRate": response["playbackRate"] / 2 }) ``` -------------------------------- ### Get Resource Timing Information for a Request (Async) Source: https://playwright.dev/python/docs/api/class-request Fetch resource timing details for a request asynchronously. Timing information becomes available upon receiving the response, with `responseEnd` populated when the request completes. This example demonstrates asynchronous event handling. ```python async with page.expect_event("requestfinished") as request_info: await page.goto("http://example.com") request = await request_info.value print(request.timing) ``` -------------------------------- ### Initialize clock with a specific time and navigate Source: https://playwright.dev/python/docs/clock Installs the clock with a specific initial time and navigates to the page. This sets up the environment for time manipulation. ```Python page.clock.install( time=datetime.datetime(2024, 2, 2, 8, 0, 0, tzinfo=datetime.timezone.pst), ) page.goto("http://localhost:3333") locator = page.get_by_test_id("current-time") ``` ```Python await page.clock.install(time= datetime.datetime(2024, 2, 2, 8, 0, 0, tzinfo=datetime.timezone.pst), ) await page.goto("http://localhost:3333") locator = page.get_by_test_id("current-time") ``` -------------------------------- ### Async APIRequestContext Example Source: https://playwright.dev/python/docs/api/class-apirequestcontext Illustrates the asynchronous usage of APIRequestContext for interacting with the GitHub API. This example mirrors the synchronous version, showing how to create and delete a repository using async/await syntax. It also utilizes a context that shares cookies with the browser. ```python import os import asyncio from playwright.async_api import async_playwright, Playwright REPO = "test-repo-1" USER = "github-username" API_TOKEN = os.getenv("GITHUB_API_TOKEN") async def run(playwright: Playwright): browser = await playwright.chromium.launch() context = await browser.new_context(base_url="https://api.github.com") api_request_context = context.request page = await context.new_page() # Create a repository. response = await api_request_context.post( "/user/repos", headers={ "Accept": "application/vnd.github.v3+json", "Authorization": f"token {API_TOKEN}", }, data={"name": REPO}, ) assert response.ok assert response.json()["name"] == REPO # Delete a repository. response = await api_request_context.delete( f"/repos/{USER}/{REPO}", headers={ "Accept": "application/vnd.github.v3+json", "Authorization": f"token {API_TOKEN}", }, ) assert response.ok assert await response.body() == '{"status": "ok"}' async def main(): async with async_playwright() as playwright: await run(playwright) asyncio.run(main()) ``` -------------------------------- ### credentials.install Source: https://playwright.dev/python/docs/api/class-credentials Installs the virtual WebAuthn authenticator into the context, overriding navigator.credentials.create() and navigator.credentials.get() in all current and future pages. Call this before the page first touches navigator.credentials. ```APIDOC ## credentials.install ### Description Installs the virtual WebAuthn authenticator into the context, overriding navigator.credentials.create() and navigator.credentials.get(). ### Method credentials.install() ### Returns #### Success Response NoneType ``` -------------------------------- ### Configure Global HTTP Proxy (Sync) Source: https://playwright.dev/python/docs/network Launch the browser with a global HTTP proxy configuration. Specify the server address, username, and password for the proxy. ```python browser = chromium.launch(proxy={ "server": "http://myproxy.com:3128", "username": "usr", "password": "pwd" }) ``` -------------------------------- ### Launch Browser, Create Context, and Page (Sync) Source: https://playwright.dev/python/docs/browser-contexts Demonstrates the synchronous way to launch a Chromium browser, create a new isolated browser context, and then create a new page within that context. ```python browser = playwright.chromium.launch() context = browser.new_context() page = context.new_page() ``` -------------------------------- ### Launch Browser, Create Context, and Page (Async) Source: https://playwright.dev/python/docs/browser-contexts Demonstrates the asynchronous way to launch a Chromium browser, create a new isolated browser context, and then create a new page within that context. ```python browser = await playwright.chromium.launch() context = await browser.new_context() page = await context.new_page() ``` -------------------------------- ### List All Installed Browsers Source: https://playwright.dev/python/docs/browsers Use this command to list all browser binaries installed by Playwright across all installations on the machine. ```bash playwright install --list ``` -------------------------------- ### Example Usage (Asynchronous) Source: https://playwright.dev/python/docs/api/class-cdpsession Demonstrates asynchronous usage of CDPSession to enable animations, subscribe to events, and get/set playback rate. ```APIDOC client = await page.context.new_cdp_session(page) await client.send("Animation.enable") client.on("Animation.animationCreated", lambda: print("animation created!")) response = await client.send("Animation.getPlaybackRate") print("playback rate is " + str(response["playbackRate"])) await client.send("Animation.setPlaybackRate", { "playbackRate": response["playbackRate"] / 2 }) ``` -------------------------------- ### Emulate Color Scheme and Media (Sync) Source: https://playwright.dev/python/docs/emulation Demonstrates creating a context and page with a specific color scheme ('dark' or 'light'), and emulating media types like 'print' synchronously. Use `emulate_media` to change settings for existing pages. ```python # Create context with dark mode context = browser.new_context( color_scheme='dark' # or 'light' ) # Create page with dark mode page = browser.new_page( color_scheme='dark' # or 'light' ) # Change color scheme for the page page.emulate_media(color_scheme='dark') # Change media for page page.emulate_media(media='print') ``` -------------------------------- ### Uninstall Playwright Browsers CLI Source: https://playwright.dev/python/docs/release-notes Use the `playwright uninstall` command to remove browsers installed by the current Playwright installation. Use `--all` to remove all browsers ever installed by Playwright. ```bash $ playwright uninstall # remove browsers installed by this installation $ playwright uninstall --all # remove all ever-install Playwright browsers ``` -------------------------------- ### Example Usage (Synchronous) Source: https://playwright.dev/python/docs/api/class-cdpsession Demonstrates synchronous usage of CDPSession to enable animations, subscribe to events, and get/set playback rate. ```APIDOC client = page.context.new_cdp_session(page) client.send("Animation.enable") client.on("Animation.animationCreated", lambda: print("animation created!")) response = client.send("Animation.getPlaybackRate") print("playback rate is " + str(response["playbackRate"])) client.send("Animation.setPlaybackRate", { "playbackRate": response["playbackRate"] / 2 }) ``` -------------------------------- ### Specify Pre-installed Node.js Path (Batch) Source: https://playwright.dev/python/docs/browsers Use the set command to define PLAYWRIGHT_NODEJS_PATH, directing Playwright to a specific Node.js installation. Ensure Playwright is installed before running the install command. ```batch set PLAYWRIGHT_NODEJS_PATH=C:\Program Files\nodejs\node.exe pip install playwright playwright install ``` -------------------------------- ### Install Playwright Browsers via HTTPS Proxy (Batch) Source: https://playwright.dev/python/docs/browsers Use this command to install Playwright browsers when behind an HTTPS proxy. Set the HTTPS_PROXY environment variable before running the install command. ```batch set HTTPS_PROXY=https://192.0.2.1 pip install playwright playwright install ``` -------------------------------- ### Configure Global HTTP Proxy (Async) Source: https://playwright.dev/python/docs/network Launch the browser asynchronously with a global HTTP proxy configuration. Specify the server address, username, and password for the proxy. ```python browser = await chromium.launch(proxy={ "server": "http://myproxy.com:3128", "username": "usr", "password": "pwd" }) ``` -------------------------------- ### context.tracing.start Source: https://playwright.dev/python/docs/api/class-tracing Starts tracing, optionally capturing screenshots and snapshots. It's recommended to enable tracing via configuration instead of direct API calls for a more complete trace. ```APIDOC ## context.tracing.start ### Description Starts tracing, optionally capturing screenshots and snapshots. It's recommended to enable tracing via configuration instead of direct API calls for a more complete trace. ### Method - `start(live: bool = False, name: str = None, screenshots: bool = False, snapshots: bool = False, sources: bool = False, title: str = None)` ### Arguments - `live` (bool, optional) - When enabled, the trace is written to an unarchived file that is updated in real time. - `name` (str, optional) - Prefix for intermediate trace files. - `screenshots` (bool, optional) - Whether to capture screenshots during tracing. - `snapshots` (bool, optional) - If true, captures DOM snapshots and records network activity. - `sources` (bool, optional) - Whether to include source files for trace actions. - `title` (str, optional) - Trace name to be shown in the Trace Viewer. ### Returns - NoneType ### Usage #### Sync ```python context.tracing.start(screenshots=True, snapshots=True) page = context.new_page() page.goto("https://playwright.dev") context.tracing.stop(path = "trace.zip") ``` #### Async ```python await context.tracing.start(screenshots=True, snapshots=True) page = await context.new_page() await page.goto("https://playwright.dev") await context.tracing.stop(path = "trace.zip") ``` ``` -------------------------------- ### Install Playwright Browsers via HTTPS Proxy (PowerShell) Source: https://playwright.dev/python/docs/browsers Use this command to install Playwright browsers when behind an HTTPS proxy. Set the HTTPS_PROXY environment variable before running the install command. ```powershell $Env:HTTPS_PROXY="https://192.0.2.1" pip install playwright playwright install ``` -------------------------------- ### Waiting for a Download (Synchronous) Source: https://playwright.dev/python/docs/api/class-download Demonstrates how to initiate an action that triggers a download and then wait for the download to complete using a synchronous context manager. ```APIDOC ## Waiting for a Download (Synchronous) ### Description This code snippet shows how to set up a listener for the `download` event and then perform an action that triggers the download. It uses `page.expect_download()` to asynchronously wait for the download to start and then retrieves the `download_info` object. ### Method ```python with page.expect_download() as download_info: page.get_by_text("Download file").click() download = download_info.value ``` ### Saving the Downloaded File ### Description After obtaining the `download` object, this demonstrates how to save the downloaded file to a specified path using the `save_as` method, combining it with the `suggested_filename` property. ### Method ```python download.save_as("/path/to/save/at/" + download.suggested_filename) ``` ``` -------------------------------- ### Install Playwright Browsers via HTTPS Proxy (Bash) Source: https://playwright.dev/python/docs/browsers Use this command to install Playwright browsers when behind an HTTPS proxy. Set the HTTPS_PROXY environment variable before running the install command. ```bash pip install playwright HTTPS_PROXY=https://192.0.2.1 playwright install ``` -------------------------------- ### Handle All New Pages with Event Listener (Sync) Source: https://playwright.dev/python/docs/pages Set up a synchronous event listener on the browser context to handle any new pages that are created. ```python # Get all new pages (including popups) in the context def handle_page(page): page.wait_for_load_state() print(page.title()) context.on("page", handle_page) ``` -------------------------------- ### Sync select_option examples Source: https://playwright.dev/python/docs/api/class-elementhandle Demonstrates synchronous usage of select_option for single and multiple selections by value or label. ```python # Single selection matching the value or label handle.select_option("blue") # single selection matching both the label handle.select_option(label="blue") # multiple selection handle.select_option(value=["red", "green", "blue"]) ``` -------------------------------- ### Install Playwright with Pip Source: https://playwright.dev/python/docs/library Installs the Playwright package and its browser binaries using pip. ```bash pip install --upgrade pip pip install playwright playwright install ``` -------------------------------- ### Install and Manage Timers with Playwright Clock (Async Python) Source: https://playwright.dev/python/docs/clock Use `await page.clock.install` to initialize the clock asynchronously. `await page.clock.pause_at` pauses time at a specific point, and `await page.clock.fast_forward` advances time. This is suitable for async tests where timers need precise control. ```python # Initialize clock with some time before the test time and let the page load # naturally. `Date.now` will progress as the timers fire. await page.clock.install(time=datetime.datetime(2024, 2, 2, 8, 0, 0)) await page.goto("http://localhost:3333") # Pretend that the user closed the laptop lid and opened it again at 10am. # Pause the time once reached that point. await page.clock.pause_at(datetime.datetime(2024, 2, 2, 10, 0, 0)) # Assert the page state. await expect(page.get_by_test_id("current-time")).to_have_text("2/2/2024, 10:00:00 AM") # Close the laptop lid again and open it at 10:30am. await page.clock.fast_forward("30:00") await expect(page.get_by_test_id("current-time")).to_have_text("2/2/2024, 10:30:00 AM") ``` -------------------------------- ### Install pytest-playwright with Pip Source: https://playwright.dev/python/docs/intro Use this command to install the pytest-playwright plugin using pip. ```bash pip install pytest-playwright ``` -------------------------------- ### Device Emulation (Async) Source: https://playwright.dev/python/docs/api/class-playwright This snippet demonstrates asynchronous device emulation using a predefined device profile like 'iPhone 6'. It uses asyncio to launch a WebKit browser with the specified context. ```python import asyncio from playwright.async_api import async_playwright, Playwright async def run(playwright: Playwright): webkit = playwright.webkit iphone = playwright.devices["iPhone 6"] browser = await webkit.launch() context = await browser.new_context(**iphone) page = await context.new_page() await page.goto("http://example.com") # other actions... await browser.close() async def main(): async with async_playwright() as playwright: await run(playwright) asyncio.run(main()) ``` -------------------------------- ### Async select_option examples Source: https://playwright.dev/python/docs/api/class-elementhandle Demonstrates asynchronous usage of select_option for single and multiple selections by value or label. ```python # Single selection matching the value or label await handle.select_option("blue") # single selection matching the label await handle.select_option(label="blue") # multiple selection await handle.select_option(value=["red", "green", "blue"]) ``` -------------------------------- ### browserType.launch Source: https://playwright.dev/python/docs/api/class-browsertype Launches a browser instance. You can use ignore_default_args to filter out '--mute-audio' from default arguments. ```APIDOC ## launch Returns the browser instance. ### Usage **Sync** ```python browser = playwright.chromium.launch( # or "firefox" or "webkit". ignore_default_args=["--mute-audio"] ) ``` **Async** ```python browser = await playwright.chromium.launch( # or "firefox" or "webkit". ignore_default_args=["--mute-audio"] ) ``` > **Chromium-only** Playwright can also be used to control the Google Chrome or Microsoft Edge browsers, but it works best with the version of Chromium it is bundled with. There is no guarantee it will work with any other version. Use executable_path option with extreme caution. > If Google Chrome (rather than Chromium) is preferred, a Chrome Canary or Dev Channel build is suggested. > Stock browsers like Google Chrome and Microsoft Edge are suitable for tests that require proprietary media codecs for video playback. See this article for other differences between Chromium and Chrome. This article describes some differences for Linux users. ### Arguments * `args` List[str] _(optional)_# warning Use custom browser args at your own risk, as some of them may break Playwright functionality. Additional arguments to pass to the browser instance. The list of Chromium flags can be found here. * `artifacts_dir` Union[str, pathlib.Path] _(optional)_# If specified, artifacts (traces, videos, downloads, HAR files, etc.) are saved into this directory. The directory is not cleaned up when the browser closes. If not specified, a temporary directory is used and cleaned up when the browser closes. * `channel` str _(optional)_# Browser distribution channel. Use "chromium" to opt in to new headless mode. Use "chrome", "chrome-beta", "chrome-dev", "chrome-canary", "msedge", "msedge-beta", "msedge-dev", or "msedge-canary" to use branded Google Chrome and Microsoft Edge. * `chromium_sandbox` bool _(optional)_# Enable Chromium sandboxing. Defaults to `false`. * `downloads_path` Union[str, pathlib.Path] _(optional)_# If specified, accepted downloads are downloaded into this directory. Otherwise, temporary directory is created and is deleted when browser is closed. In either case, the downloads are deleted when the browser context they were created in is closed. * `env` Dict[str, str | float | bool] _(optional)_# Specify environment variables that will be visible to the browser. Defaults to `process.env`. * `executable_path` Union[str, pathlib.Path] _(optional)_# Path to a browser executable to run instead of the bundled one. If executable_path is a relative path, then it is resolved relative to the current working directory. Note that Playwright only works with the bundled Chromium, Firefox or WebKit, use at your own risk. * `firefox_user_prefs` Dict[str, str | float | bool] _(optional)_# Firefox user preferences. Learn more about the Firefox user preferences at `about:config`. You can also provide a path to a custom `policies.json` file via `PLAYWRIGHT_FIREFOX_POLICIES_JSON` environment variable. * `handle_sighup` bool _(optional)_# Close the browser process on SIGHUP. Defaults to `true`. * `handle_sigint` bool _(optional)_# Close the browser process on Ctrl-C. Defaults to `true`. * `handle_sigterm` bool _(optional)_# Close the browser process on SIGTERM. Defaults to `true`. * `headless` bool _(optional)_# Whether to run browser in headless mode. More details for Chromium and Firefox. Defaults to `true`. * `ignore_default_args` bool | List[str] _(optional)_# If `true`, Playwright does not pass its own configurations args and only uses the ones from args. If an array is given, then filters out the given default arguments. Dangerous option; use with care. Defaults to `false`. * `proxy` Dict _(optional)_# * `server` str Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example `http://myproxy.com:3128` or `socks5://myproxy.com:3128`. Short form `myproxy.com:3128` is considered an HTTP proxy. * `bypass` str _(optional)_ Optional comma-separated domains to bypass proxy, for example `".com, chromium.org, .domain.com"`. * `username` str _(optional)_ Optional username to use if HTTP proxy requires authentication. * `password` str _(optional)_ Optional password to use if HTTP proxy requires authentication. Network proxy settings. * `slow_mo` float _(optional)_# Slows down Playwright operations by the specified amount of milliseconds. Useful so that you can see what is going on. * `timeout` float _(optional)_# Maximum time in milliseconds to wait for the browser instance to start. Defaults to `30000` (30 seconds). Pass `0` to disable timeout. * `traces_dir` Union[str, pathlib.Path] _(optional)_# If specified, traces are saved into this directory. ### Returns * Browser# ``` -------------------------------- ### Uninstall All Playwright Installation Browsers Source: https://playwright.dev/python/docs/browsers Removes browser binaries for all Playwright installations on the machine. Use with caution. ```bash playwright uninstall --all ``` -------------------------------- ### Get Request Method - Python Source: https://playwright.dev/python/docs/api/class-request Retrieves the HTTP method used for the request (e.g., GET, POST). ```python request.method ``` -------------------------------- ### Uninstall Current Playwright Installation Browsers Source: https://playwright.dev/python/docs/browsers Removes the browser binaries (Chromium, Firefox, WebKit) associated with the current Playwright installation. ```bash playwright uninstall ``` -------------------------------- ### HTML for Visible Elements Example Source: https://playwright.dev/python/docs/locators This HTML snippet demonstrates the structure used in the Playwright examples for matching visible and invisible elements. ```html ``` -------------------------------- ### Handle All New Pages with Event Listener (Async) Source: https://playwright.dev/python/docs/pages Set up an asynchronous event listener on the browser context to handle any new pages that are created. ```python # Get all new pages (including popups) in the context async def handle_page(page): await page.wait_for_load_state() print(await page.title()) context.on("page", handle_page) ``` -------------------------------- ### Device Emulation (Sync) Source: https://playwright.dev/python/docs/api/class-playwright This snippet demonstrates synchronous device emulation using a predefined device profile like 'iPhone 6'. It launches a WebKit browser with the specified context. ```python from playwright.sync_api import sync_playwright, Playwright def run(playwright: Playwright): webkit = playwright.webkit iphone = playwright.devices["iPhone 6"] browser = webkit.launch() context = browser.new_context(**iphone) page = context.new_page() page.goto("http://example.com") # other actions... browser.close() with sync_playwright() as playwright: run(playwright) ``` -------------------------------- ### Install Specific Playwright Browser Source: https://playwright.dev/python/docs/browsers Install a specific browser (e.g., WebKit) by providing its name as an argument. Use this when you only need certain browsers. ```bash playwright install webkit ``` -------------------------------- ### Basic GET Request and Assertion (Sync) Source: https://playwright.dev/python/docs/api/class-apiresponseassertions Demonstrates making a GET request and asserting that the response is OK using synchronous Playwright API. ```python from playwright.sync_api import Page, expect def test_navigates_to_login_page(page: Page) -> None: # .. response = page.request.get('https://playwright.dev') expect(response).to_be_ok() ``` -------------------------------- ### Record video with browser context (Async) Source: https://playwright.dev/python/docs/videos Asynchronously create a new browser context and specify the directory for video recordings. Await the context closure to ensure videos are saved. ```python context = await browser.new_context(record_video_dir="videos/") # Make sure to await close, so that videos are saved. await context.close() ``` -------------------------------- ### Configure Context HTTP Proxy (Sync) Source: https://playwright.dev/python/docs/network Create a new browser context with a specific HTTP proxy configuration. This allows for per-context proxy settings. ```python browser = chromium.launch() context = browser.new_context(proxy={"server": "http://myproxy.com:3128"}) ``` -------------------------------- ### Install System Dependencies for a Single Browser Source: https://playwright.dev/python/docs/browsers Install system dependencies specifically for a single browser, such as Chromium. This can save space if you only use a subset of browsers. ```bash playwright install-deps chromium ``` -------------------------------- ### Configure Context HTTP Proxy (Async) Source: https://playwright.dev/python/docs/network Create a new browser context asynchronously with a specific HTTP proxy configuration. This allows for per-context proxy settings. ```python browser = await chromium.launch() context = await browser.new_context(proxy={"server": "http://myproxy.com:3128"}) ``` -------------------------------- ### Get frame object and interact (Async) Source: https://playwright.dev/python/docs/frames The asynchronous approach to getting a frame object and performing actions within it. Use `await` for all Playwright interactions. ```python frame = page.frame('frame-login') frame = page.frame(url=r'.*domain.*') await frame.fill('#username-input', 'John') ``` -------------------------------- ### Navigate to URL (Sync) Source: https://playwright.dev/python/docs/navigations Use page.goto() to load a URL in sync mode. This waits for the 'load' event. ```python # Navigate the page page.goto("https://example.com") ``` -------------------------------- ### Basic GET Request and Assertion (Async) Source: https://playwright.dev/python/docs/api/class-apiresponseassertions Demonstrates making an asynchronous GET request and asserting that the response is OK using asynchronous Playwright API. ```python from playwright.async_api import Page, expect async def test_navigates_to_login_page(page: Page) -> None: # .. response = await page.request.get('https://playwright.dev') await expect(response).to_be_ok() ``` -------------------------------- ### Start Selenium Node Source: https://playwright.dev/python/docs/selenium-grid Command to start a Selenium node, ensuring it registers with the Selenium Grid Hub. Set SE_NODE_GRID_URL to the hub's address. ```bash # Start selenium node SE_NODE_GRID_URL="http://:4444" java -jar selenium-server-.jar node ``` -------------------------------- ### Install Playwright and Specify Browser Path (PowerShell) Source: https://playwright.dev/python/docs/browsers Install Playwright and instruct it to download browsers into a custom directory using the PLAYWRIGHT_BROWSERS_PATH environment variable in PowerShell. ```powershell $Env:PLAYWRIGHT_BROWSERS_PATH="$Env:USERPROFILE\pw-browsers" pip install playwright playwright install ```