Skip to main content
Version: 1.12.0

Core concepts

Playwright provides a set of APIs to automate Chromium, Firefox and WebKit browsers. By using the Playwright API, you can write scripts to create new browser pages, navigate to URLs and then interact with elements on a page.

Along with a test runner Playwright can be used to automate user interactions to validate and test web applications. The Playwright API enables this through the following primitives.


Browser#

A Browser refers to an instance of Chromium, Firefox or WebKit. Playwright scripts generally start with launching a browser instance and end with closing the browser. Browser instances can be launched in headless (without a GUI) or headed mode.

using Microsoft.Playwright;
using System.Threading.Tasks;
class Program
{
public static async Task Main()
{
using var playwright = await Playwright.CreateAsync();
await using var firefox = playwright.Firefox.LaunchAsync(new BrowserTypeLaunchOptions
{
Headless = false
});
}
}

Launching a browser instance can be expensive, and Playwright is designed to maximize what a single instance can do through multiple browser contexts.

API reference#


Browser contexts#

A BrowserContext is an isolated incognito-alike session within a browser instance. Browser contexts are fast and cheap to create. We recommend running each test scenario in its own new Browser context, so that the browser state is isolated between the tests.

await using var browser = playwright.Chromium.LaunchAsync();
var context = await browser.NewContextAsync();

Browser contexts can also be used to emulate multi-page scenarios involving mobile devices, permissions, locale and color scheme.

using Microsoft.Playwright;
using System.Threading.Tasks;
class PlaywrightExample
{
public static async Task Main()
{
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Webkit.LaunchAsync();
var options = new BrowserContextNewOptions(Playwright.Devices["iPhone 11 Pro"])
{
Geolocation = new Geolocation() { Longitude = 12.492507f, Latitude = 41.889938f },
Permissions = new[] { "geolocation" },
Locale = "de-DE"
};
await using var context = await browser.NewContextAsync(options);
// do work
}
}

API reference#


Pages and frames#

A Browser context can have multiple pages. A Page refers to a single tab or a popup window within a browser context. It should be used to navigate to URLs and interact with the page content.

// Create a page.
var page = await context.NewPageAsync();
// Navigate explicitly, similar to entering a URL in the browser.
await page.GotoAsync("http://example.com");
// Fill an input.
await page.FillAsync("#search", "query");
// Navigate implicitly by clicking a link.
await page.ClickAsync("#submit");
// Expect a new url.
Console.WriteLine(page.Url);
// Page can navigate from the script - this will be picked up by Playwright.
// window.location.href = "https://example.com";

Read more on page navigation and loading.

A page can have one or more Frame objects attached to it. Each page has a main frame and page-level interactions (like click) are assumed to operate in the main frame.

A page can have additional frames attached with the iframe HTML tag. These frames can be accessed for interactions inside the frame.

// Create a page.
var page = await context.NewPageAsync();
// Get frame using the frame's name attribute
var frame = page.Frame("frame-login");
// Get frame using frame's URL
var frame = page.FrameByUrl("*domain.");
// Get frame using any other selector
var frameElementHandle = await page.QuerySelectorAsync(".frame-class");
var frame = await frameElementHandle.ContentFrameAsync();
// Interact with the frame
await frame.FillAsync("#username-input", "John");

API reference#


Selectors#

Playwright can search for elements using CSS selectors, XPath selectors, HTML attributes like id, data-test-id and even text content.

You can explicitly specify the selector engine you are using or let Playwright detect it.

All selector engines except for XPath pierce shadow DOM by default. If you want to enforce regular DOM selection, you can use the *:light versions of the selectors. You don't typically need to though.

Learn more about selectors and selector engines here.

Some examples below:

// Using data-test-id= selector engine
await page.ClickAsync("data-test-id=foo");
// CSS and XPath selector engines are automatically detected
await page.ClickAsync("div");
await page.ClickAsync("//html/body/div");
// Find node by text substring
await page.ClickAsync("text=Hello w");
// Explicit CSS and XPath notation
await page.ClickAsync("css=div");
await page.ClickAsync("xpath=//html/body/div");
// Only search light DOM, outside WebComponent shadow DOM:
await page.ClickAsync("css:light=div");

Selectors using the same or different engines can be combined using the >> separator. For example,

// Click an element with text "Sign Up" inside of a #free-month-promo.
await page.Click("#free-month-promo >> text=Sign Up");
// Capture textContent of a section that contains an element with text "Selectors".
var sectionText = await page.EvalOnSelectorAsync<string>("*css=section >> text=Selectors", "e => e.textContent");

Auto-waiting#

Actions like Page.ClickAsync(selector, options) and Page.FillAsync(selector, value, options) auto-wait for the element to be visible and actionable. For example, click will:

  • wait for an element with the given selector to appear in the DOM
  • wait for it to become visible: have non-empty bounding box and no visibility:hidden
  • wait for it to stop moving: for example, wait until css transition finishes
  • scroll the element into view
  • wait for it to receive pointer events at the action point: for example, wait until element becomes non-obscured by other elements
  • retry if the element is detached during any of the above checks
// Playwright waits for #search element to be in the DOM
await page.FillAsync("#search", "query");
// Playwright waits for element to stop animating
// and accept clicks.
await page.ClickAsync("#search");

You can explicitly wait for an element to appear in the DOM or to become visible:

// Wait for #search to appear in the DOM.
await page.WaitForSelectorAsync("#search", WaitForSelectorState.Attached);
// Wait for #promo to become visible, for example with `visibility:visible`.
await page.WaitForSelectorAsync("#promo");

... or to become hidden or detached

// Wait for #details to become hidden, for example with "display:none".
await page.WaitForSelectorAsync("#details", WaitForSelectorState.Hidden);
// Wait for #promo to be removed from the DOM.
await page.WaitForSelectorAsync("#promo", WaitForSelectorState.Detached);

API reference#


Execution contexts: Playwright and Browser#

Playwright scripts run in your Playwright environment. Your page scripts run in the browser page environment. Those environments don't intersect, they are running in different virtual machines in different processes and even potentially on different computers.

The Page.EvaluateAsync(expression, arg) API can run a JavaScript function in the context of the web page and bring results back to the Playwright environment. Browser globals like window and document can be used in evaluate.

var href = await page.EvaluateAsync<string>("document.location.href");

If the result is a Promise or if the function is asynchronous evaluate will automatically wait until it's resolved:

int status = await page.EvaluateAsync<int>(@"async () => {
const response = await fetch(location.href);
return response.status;
}");

Evaluation Argument#

Playwright evaluation methods like Page.EvaluateAsync(expression, arg) take a single optional argument. This argument can be a mix of Serializable values and JSHandle or ElementHandle instances. Handles are automatically converted to the value they represent.

// A primitive value.
await page.EvaluateAsync<int>("num => num", 42);
// An array.
await page.EvaluateAsync<int[]>("array => array.length", new[] { 1, 2, 3 });
// An object.
await page.EvaluateAsync<object>("object => object.foo", new { foo = "bar" });
// A single handle.
var button = await page.QuerySelectorAsync("button");
await page.EvaluateAsync<IJSHandle>("button => button.textContent", button);
// Alternative notation using elementHandle.EvaluateAsync.
await button.EvaluateAsync<string>("(button, from) => button.textContent.substring(from)", 5);
// Object with multiple handles.
var button1 = await page.QuerySelectorAsync(".button1");
var button2 = await page.QuerySelectorAsync(".button2");
await page.EvaluateAsync("o => o.button1.textContent + o.button2.textContent", new { button1, button2 });
// Object destructuring works. Note that property names must match
// between the destructured object and the argument.
// Also note the required parenthesis.
await page.EvaluateAsync("({ button1, button2 }) => button1.textContent + button2.textContent", new { button1, button2 });
// Array works as well. Arbitrary names can be used for destructuring.
// Note the required parenthesis.
await page.EvaluateAsync("([b1, b2]) => b1.textContent + b2.textContent", new[] { button1, button2 });
// Any non-cyclic mix of serializables and handles works.
await page.EvaluateAsync("x => x.button1.textContent + x.list[0].textContent + String(x.foo)", new { button1, list = new[] { button2 }, foo = null as object });

Right:

var data = new { text = "some data", value = 1};
// Pass data as a parameter
var result = await page.EvaluateAsync("data => { window.myApp.use(data); }", data);

Wrong:

var data = new { text = "some data", value = 1};
// Pass data as a parameter
var result = await page.EvaluateAsync(@"data => {
// There is no |data| in the web page.
window.myApp.use(data);
}");

API reference#