From e55a2bdf16c1ded0465e6a0aaf98e383ce2bd0c0 Mon Sep 17 00:00:00 2001 From: Dmitry Gozman Date: Fri, 2 Dec 2022 21:48:37 -0800 Subject: [PATCH] docs: rework Selectors to Other Locators (#19244) - Replace links to `selectors.md` with `locators.md`. - Remove sections that are covered by Locators docs. - Restructure the rest of selectors doc, update them in terms of locators. Fixes #18992. --- docs/src/api/class-elementhandle.md | 12 +- docs/src/api/class-frame.md | 11 +- docs/src/api/class-playwright.md | 2 +- docs/src/api/class-selectors.md | 2 +- docs/src/api/params.md | 13 +- docs/src/ci-intro-js.md | 6 +- docs/src/debug.md | 5 +- docs/src/locators.md | 8 +- docs/src/{selectors.md => other-locators.md} | 1200 +++++++++--------- docs/src/protractor-js.md | 3 +- docs/src/puppeteer-js.md | 3 +- docs/src/release-notes-csharp.md | 14 +- docs/src/release-notes-java.md | 20 +- docs/src/release-notes-js.md | 20 +- docs/src/release-notes-python.md | 20 +- docs/src/running-tests-csharp.md | 4 +- docs/src/running-tests-js.md | 4 +- docs/src/running-tests-python.md | 2 +- docs/src/testing-library-js.md | 3 +- docs/src/why-playwright.md | 4 +- docs/src/writing-tests-java.md | 2 +- packages/playwright-core/types/types.d.ts | 300 +++-- 22 files changed, 793 insertions(+), 865 deletions(-) rename docs/src/{selectors.md => other-locators.md} (50%) diff --git a/docs/src/api/class-elementhandle.md b/docs/src/api/class-elementhandle.md index 2861d04abe..1b5f2621ff 100644 --- a/docs/src/api/class-elementhandle.md +++ b/docs/src/api/class-elementhandle.md @@ -379,8 +379,7 @@ Optional event-specific initialization properties. Returns the return value of [`param: expression`]. The method finds an element matching the specified selector in the `ElementHandle`s subtree and passes it as a first -argument to [`param: expression`]. See [Working with selectors](../selectors.md) for more -details. If no elements match the selector, the method throws an error. +argument to [`param: expression`]. If no elements match the selector, the method throws an error. If [`param: expression`] returns a [Promise], then [`method: ElementHandle.evalOnSelector`] would wait for the promise to resolve and return its value. @@ -439,8 +438,7 @@ Optional argument to pass to [`param: expression`]. Returns the return value of [`param: expression`]. The method finds all elements matching the specified selector in the `ElementHandle`'s subtree and passes an array of -matched elements as a first argument to [`param: expression`]. See -[Working with selectors](../selectors.md) for more details. +matched elements as a first argument to [`param: expression`]. If [`param: expression`] returns a [Promise], then [`method: ElementHandle.evalOnSelectorAll`] would wait for the promise to resolve and return its value. @@ -677,8 +675,7 @@ Time to wait between `keydown` and `keyup` in milliseconds. Defaults to 0. - alias-js: $ - returns: <[null]|[ElementHandle]> -The method finds an element matching the specified selector in the `ElementHandle`'s subtree. See -[Working with selectors](../selectors.md) for more details. If no elements match the selector, +The method finds an element matching the specified selector in the `ElementHandle`'s subtree. If no elements match the selector, returns `null`. ### param: ElementHandle.querySelector.selector = %%-query-selector-%% @@ -691,8 +688,7 @@ returns `null`. - alias-js: $$ - returns: <[Array]<[ElementHandle]>> -The method finds all elements matching the specified selector in the `ElementHandle`s subtree. See -[Working with selectors](../selectors.md) for more details. If no elements match the selector, +The method finds all elements matching the specified selector in the `ElementHandle`s subtree. If no elements match the selector, returns empty array. ### param: ElementHandle.querySelectorAll.selector = %%-query-selector-%% diff --git a/docs/src/api/class-frame.md b/docs/src/api/class-frame.md index 5f38257e53..49b77defd3 100644 --- a/docs/src/api/class-frame.md +++ b/docs/src/api/class-frame.md @@ -479,7 +479,7 @@ Optional event-specific initialization properties. Returns the return value of [`param: expression`]. The method finds an element matching the specified selector within the frame and passes it as a first argument to -[`param: expression`]. See [Working with selectors](../selectors.md) for more details. If no +[`param: expression`]. If no elements match the selector, the method throws an error. If [`param: expression`] returns a [Promise], then [`method: Frame.evalOnSelector`] would wait for the promise to resolve and return its @@ -544,8 +544,7 @@ Optional argument to pass to [`param: expression`]. Returns the return value of [`param: expression`]. The method finds all elements matching the specified selector within the frame and passes an array of matched elements -as a first argument to [`param: expression`]. See [Working with selectors](../selectors.md) for -more details. +as a first argument to [`param: expression`]. If [`param: expression`] returns a [Promise], then [`method: Frame.evalOnSelectorAll`] would wait for the promise to resolve and return its value. @@ -1367,8 +1366,7 @@ Returns the ElementHandle pointing to the frame element. The use of [ElementHandle] is discouraged, use [Locator] objects and web-first assertions instead. ::: -The method finds an element matching the specified selector within the frame. See -[Working with selectors](../selectors.md) for more details. If no elements match the selector, +The method finds an element matching the specified selector within the frame. If no elements match the selector, returns `null`. ### param: Frame.querySelector.selector = %%-query-selector-%% @@ -1391,8 +1389,7 @@ Returns the ElementHandles pointing to the frame elements. The use of [ElementHandle] is discouraged, use [Locator] objects instead. ::: -The method finds all elements matching the specified selector within the frame. See -[Working with selectors](../selectors.md) for more details. If no elements match the selector, +The method finds all elements matching the specified selector within the frame. If no elements match the selector, returns empty array. ### param: Frame.querySelectorAll.selector = %%-query-selector-%% diff --git a/docs/src/api/class-playwright.md b/docs/src/api/class-playwright.md index ca1e866ddd..843b0b9f1c 100644 --- a/docs/src/api/class-playwright.md +++ b/docs/src/api/class-playwright.md @@ -233,7 +233,7 @@ Exposes API that can be used for the Web API testing. - type: <[Selectors]> Selectors can be used to install custom selector engines. See -[Working with selectors](../selectors.md) for more information. +[extensibility](../extensibility.md) for more information. ## property: Playwright.webkit * since: v1.8 diff --git a/docs/src/api/class-selectors.md b/docs/src/api/class-selectors.md index 3d6c3874b6..897f0fab4d 100644 --- a/docs/src/api/class-selectors.md +++ b/docs/src/api/class-selectors.md @@ -1,7 +1,7 @@ # class: Selectors * since: v1.8 -Selectors can be used to install custom selector engines. See [Working with selectors](../selectors.md) for more +Selectors can be used to install custom selector engines. See [extensibility](../extensibility.md) for more information. ## async method: Selectors.register diff --git a/docs/src/api/params.md b/docs/src/api/params.md index a4bd5ab17d..250e9412cd 100644 --- a/docs/src/api/params.md +++ b/docs/src/api/params.md @@ -51,20 +51,17 @@ Whether to bypass the [actionability](../actionability.md) checks. Defaults to ` ## input-selector - `selector` <[string]> -A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used. See -[working with selectors](../selectors.md) for more details. +A selector to search for an element. If there are multiple elements satisfying the selector, the first will be used. ## input-source - `source` <[string]> -A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used. See -[working with selectors](../selectors.md) for more details. +A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will be used. ## input-target - `target` <[string]> -A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will be used. See -[working with selectors](../selectors.md) for more details. +A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first will be used. ## input-position - `position` <[Object]> @@ -130,12 +127,12 @@ Whether to check or uncheck the checkbox. ## query-selector - `selector` <[string]> -A selector to query for. See [working with selectors](../selectors.md) for more details. +A selector to query for. ## find-selector - `selector` <[string]> -A selector to use when resolving DOM element. See [working with selectors](../selectors.md) for more details. +A selector to use when resolving DOM element. ## wait-for-selector-state - `state` <[WaitForSelectorState]<"attached"|"detached"|"visible"|"hidden">> diff --git a/docs/src/ci-intro-js.md b/docs/src/ci-intro-js.md index 61fac26511..01f9235180 100644 --- a/docs/src/ci-intro-js.md +++ b/docs/src/ci-intro-js.md @@ -110,6 +110,6 @@ To learn more about running tests on CI check out our detailed guide on [Continu ## What's Next -- [Learn how to use Web First Assertions](/test-assertions.md) -- [Learn how to use Selectors](/selectors.md) -- [Learn how to use Locators](/locators.md) +- [Learn how to use Locators](./locators.md) +- [Learn how to perform Actions](./input.md) +- [Learn how to write Assertions](./test-assertions.md) diff --git a/docs/src/debug.md b/docs/src/debug.md index fe8607493e..e0cad775d9 100644 --- a/docs/src/debug.md +++ b/docs/src/debug.md @@ -107,8 +107,7 @@ Using `PWDEBUG=console` will configure the browser for debugging in Developer to - **Runs headed**: Browsers always launch in headed mode - **Disables timeout**: Sets default timeout to 0 (= no timeout) - **Console helper**: Configures a `playwright` object in the browser to generate and highlight - [Playwright selectors](./selectors.md). This can be used to verify text or - composite selectors. + [Playwright locators](./locators.md). This can be used to verify locators. ```bash tab=bash-bash lang=js PWDEBUG=console npx playwright test @@ -201,7 +200,7 @@ pwsh bin/Debug/netX/playwright.ps1 codegen wikipedia.org ### Stepping through the Playwright script -The Inspector opens up a browser window highlighting the selectors as you step through each line of the test. Use the explore button to find other available [selectors](./selectors.md) which you can then copy into your test file and rerun your tests to see if they pass. +The Inspector opens up a browser window highlighting the elements as you step through each line of the test. Use the explore button to pick a [locator](./locators.md) which you can then copy into your test file and rerun your tests to see if they pass. Paused on line diff --git a/docs/src/locators.md b/docs/src/locators.md index 12e56e6cb5..71db0ca3ba 100644 --- a/docs/src/locators.md +++ b/docs/src/locators.md @@ -258,7 +258,7 @@ await page .ClickAsync(); ``` -Role locators include [buttons, checkboxes, headings, links, lists, tables, and many more](https://www.w3.org/TR/html-aria/#docconformance) and follow W3C specifications for [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles), [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). +Role locators include [buttons, checkboxes, headings, links, lists, tables, and many more](https://www.w3.org/TR/html-aria/#docconformance) and follow W3C specifications for [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles), [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). Note that many html elements like ``. +### CSS: matching by text - ```js - await page.locator('text=Log in').click(); - ``` - ```java - page.locator("text=Log in").click(); - ``` - ```python async - await page.locator("text=Log in").click() - ``` - ```python sync - page.locator("text=Log in").click() - ``` - ```csharp - await page.Locator("text=Log in").ClickAsync(); - ``` +Playwright include a number of CSS pseudo-classes to match elements by their text content. -- `text="Log in"` - text body can be escaped with single or double quotes to search for a text node with exact content after trimming whitespace. For example, `text="Log"` does not match `` because ``, because ``. +- `article:has-text("Playwright")` - the `:has-text()` matches any element containing specified text somewhere inside, possibly in a child or a descendant element. Matching is case-insensitive, trims whitestapce and searches for a substring. - Quoted body follows the usual escaping rules, e.g. use `\"` to escape double quote in a double-quoted string: `text="foo\"bar"`. + For example, `article:has-text("Playwright")` matches `
Playwright
`. - ```js - await page.locator('text="Log in"').click(); - ``` - ```java - page.locator("text='Log in'").click(); - ``` - ```python async - await page.locator("text='Log in'").click() - ``` - ```python sync - page.locator("text='Log in'").click() - ``` - ```csharp - await page.Locator("text='Log in'").ClickAsync(); - ``` - -- `"Log in"` - selector starting and ending with a quote (either `"` or `'`) is assumed to be a text selector. For example, `"Log in"` is converted to `text="Log in"` internally. - - ```js - await page.locator('"Log in"').click(); - ``` - ```java - page.locator("'Log in'").click(); - ``` - ```python async - await page.locator("'Log in'").click() - ``` - ```python sync - page.locator("'Log in'").click() - ``` - ```csharp - await page.Locator("'Log in'").ClickAsync(); - ``` - -- `/Log\s*in/i` - body can be a [JavaScript-like regex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) wrapped in `/` symbols. For example, `text=/Log\s*in/i` matches `` and ``. - - ```js - await page.locator('text=/Log\\s*in/i').click(); - ``` - ```java - page.locator("text=/Log\\s*in/i").click(); - ``` - ```python async - await page.locator("text=/Log\s*in/i").click() - ``` - ```python sync - page.locator("text=/Log\s*in/i").click() - ``` - ```csharp - await page.Locator("text=/Log\\s*in/i").ClickAsync(); - ``` - -- `article:has-text("Playwright")` - the `:has-text()` pseudo-class can be used inside a [css] selector. It matches any element containing specified text somewhere inside, possibly in a child or a descendant element. Matching is case-insensitive, trims whitestapce and searches for a substring. For example, `article:has-text("Playwright")` matches `
Playwright
`. - - Note that `:has-text()` should be used together with other `css` specifiers, otherwise it will match all the elements containing specified text, including the ``. + Note that `:has-text()` should be used together with other CSS specifiers, otherwise it will match all the elements containing specified text, including the ``. ```js // Wrong, will match many elements including await page.locator(':has-text("Playwright")').click(); @@ -141,7 +81,9 @@ Text selector has a few variations: await page.Locator("article:has-text(\"Playwright\")").ClickAsync(); ``` -- `#nav-bar :text("Home")` - the `:text()` pseudo-class can be used inside a [css] selector. It matches the smallest element containing specified text. This example is equivalent to `text=Home`, but inside the `#nav-bar` element. +- `#nav-bar :text("Home")` - the `:text()` pseudo-class matches the smallest element containing specified text. Matching is case-insensitive, trims whitespace and searches for a substring. + + For example, this will find an element with text "Home" somewhere inside the `#nav-bar` element: ```js await page.locator('#nav-bar :text("Home")').click(); @@ -159,60 +101,28 @@ Text selector has a few variations: await page.Locator("#nav-bar :text('Home')").ClickAsync(); ``` -- `#nav-bar :text-is("Home")` - the `:text-is()` pseudo-class can be used inside a [css] selector, for strict text node match. This example is equivalent to `text="Home"` (note quotes), but inside the `#nav-bar` element. +- `#nav-bar :text-is("Home")` - the `:text-is()` pseudo-class matches the smallest element with exact text. Exact matching is case-sensitive, trims whitespace and searches for the full string. -* `#nav-bar :text-matches("reg?ex", "i")` - the `:text-matches()` pseudo-class can be used inside a [css] selector, for regex-based match. This example is equivalent to `text=/reg?ex/i`, but inside the `#nav-bar` element. + For example, `:text-is("Log")` does not match `` because ``, because `` because it is case-sensitive. + +* `#nav-bar :text-matches("reg?ex", "i")` - the `:text-matches()` pseudo-class matches the smallest element with text content matching the [JavaScript-like regex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp). + + For example, `:text-matches("Log\s*in", "i")` matches `` and ``. :::note -Matching always normalizes whitespace. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace. +Text matching always normalizes whitespace. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace. ::: :::note -Input elements of the type `button` and `submit` are matched by their `value` instead of text content. For example, `text=Log in` matches ``. +Input elements of the type `button` and `submit` are matched by their `value` instead of text content. For example, `:text("Log in")` matches ``. ::: -## CSS selector -Playwright augments standard CSS selectors in two ways: -* `css` engine pierces open shadow DOM by default. -* Playwright adds custom pseudo-classes like `:visible`, `:text` and more. +### CSS: matching only visible elements -```js -await page.locator('button').click(); -``` - -```java -page.locator("button").click(); -``` - -```python async -await page.locator("button").click() -``` - -```python sync -page.locator("button").click() -``` - -```csharp -await page.Locator("button").ClickAsync(); -``` - -## Selecting visible elements - -There are two ways of selecting only [visible](./actionability.md#visible) elements with Playwright: -- `:visible` pseudo-class in CSS selectors -- `visible=` selector engine - -If you prefer your selectors to be CSS and don't want to rely on [chaining selectors](#chaining-selectors), use `:visible` pseudo class like so: `input:visible`. If you prefer combining selector engines, use `input >> visible=true`. The latter allows you to combine `text=`, `xpath=` and other selector engines with the visibility filter. - -For example, `input` matches all the inputs on the page, while -`input:visible` and `input >> visible=true` only match visible inputs. This is useful to distinguish elements -that are very similar but differ in visibility. - -:::note -It's usually better to follow the [best practices](#best-practices) and find a more reliable way to -uniquely identify the element. -::: +Playwrigt supports the `:visible` pseudo class in CSS selectors. For example, `css=button` matches all the buttons on the page, while `css=button:visible` only matches visible buttons. This is useful to distinguish elements that are very similar but differ in visibility. Consider a page with two buttons, first invisible and second visible. @@ -221,7 +131,7 @@ Consider a page with two buttons, first invisible and second visible. ``` -* This will find the first button because it is the first element in DOM order. Then it will wait for the button to become visible before clicking, or timeout while waiting: +* This will find both buttons and throw a [strictness](./locators.md#strictness) violation error: ```js await page.locator('button').click(); @@ -243,79 +153,28 @@ Consider a page with two buttons, first invisible and second visible. await page.Locator("button").ClickAsync(); ``` -* These will find a second button, because it is visible, and then click it. +* This will only find a second button, because it is visible, and then click it. ```js await page.locator('button:visible').click(); - await page.locator('button >> visible=true').click(); ``` ```java page.locator("button:visible").click(); - page.locator("button >> visible=true").click(); ``` ```python async await page.locator("button:visible").click() - await page.locator("button >> visible=true").click() ``` ```python sync page.locator("button:visible").click() - page.locator("button >> visible=true").click() ``` ```csharp await page.Locator("button:visible").ClickAsync(); - await page.Locator("button >> visible=true").ClickAsync(); ``` -## Selecting elements that contain other elements - -### Filter by text - -Locators support an option to only select elements that have some text somewhere inside, possibly in a descendant element. Matching is case-insensitive and searches for a substring. - - ```js - await page.locator('button', { hasText: 'Click me' }).click(); - ``` - ```java - page.locator("button", new Page.LocatorOptions().setHasText("Click me")).click(); - ``` - ```python async - await page.locator("button", has_text="Click me").click() - ``` - ```python sync - page.locator("button", has_text="Click me").click() - ``` - ```csharp - await page.Locator("button", new() { HasText = "Click me" }).ClickAsync(); - ``` - -You can also pass a regular expression. - -### Filter by another locator - -Locators support an option to only select elements that have a descendant matching another locator. - - ```js - page.locator('article', { has: page.locator('button.subscribe') }) - ``` - ```java - page.locator("article", new Page.LocatorOptions().setHas(page.locator("button.subscribe"))) - ``` - ```python async - page.locator("article", has=page.locator("button.subscribe")) - ``` - ```python sync - page.locator("article", has=page.locator("button.subscribe")) - ``` - ```csharp - page.Locator("article", new() { Has = page.Locator("button.subscribe") }) - ``` - -Note that inner locator is matched starting from the outer one, not from the document root. - -### Inside CSS selector +### CSS: elements that contain other elements The `:has()` pseudo-class is an [experimental CSS pseudo-class](https://developer.mozilla.org/en-US/docs/Web/CSS/:has). It returns an element if any of the selectors passed as parameters -relative to the :scope of the given element match at least one element. +relative to the `:scope` of the given element match at least one element. Following snippet returns text content of an `
` element that has a `
` inside. @@ -339,39 +198,7 @@ page.locator("article:has(div.promo)").text_content() await page.Locator("article:has(div.promo)").TextContentAsync(); ``` -## Augmenting existing locators - -You can add filtering to any locator by passing `:scope` selector to [`method: Locator.locator`] and specifying desired options. For example, given the locator `row` that selects some rows in the table, you can filter to just those that contain text "Hello". - - ```js - const row = page.locator('.row'); - // ... later on ... - await row.locator(':scope', { hasText: 'Hello' }).click(); - ``` - ```java - Locator row = page.locator(".row"); - // ... later on ... - row.locator(":scope", new Locator.LocatorOptions().setHasText("Hello")).click(); - ``` - ```python async - row = page.locator(".row") - # ... later on ... - await row.locator(":scope", has_text="Hello").click() - ``` - ```python sync - row = page.locator(".row") - # ... later on ... - row.locator(":scope", has_text="Hello").click() - ``` - ```csharp - var locator = page.Locator(".row"); - // ... later on ... - await locator.Locator(":scope", new() { HasText = "Hello" }).ClickAsync(); - ``` - -## Selecting elements matching one of the conditions - -### CSS selector list +### CSS: elements matching one of the conditions Comma-separated list of CSS selectors will match all elements that can be selected by one of the selectors in that list. @@ -404,116 +231,26 @@ await page.Locator("button:has-text(\"Log in\"), button:has-text(\"Sign in\")"). The `:is()` pseudo-class is an [experimental CSS pseudo-class](https://developer.mozilla.org/en-US/docs/Web/CSS/:is) that may be useful for specifying a list of extra conditions on an element. -### XPath union -Pipe operator (`|`) can be used to specify multiple selectors in XPath. It will match all -elements that can be selected by one of the selectors in that list. +### CSS: matching elements based on layout -```js -// Waits for either confirmation dialog or load spinner. -await page.locator(`//span[contains(@class, 'spinner__loading')]|//div[@id='confirmation']`).waitFor(); -``` +:::note +Matching based on layout may produce unexpected results. For example, a different element could be matched when layout changes by one pixel. +::: -```java -// Waits for either confirmation dialog or load spinner. -page.locator("//span[contains(@class, 'spinner__loading')]|//div[@id='confirmation']").waitFor(); -``` - -```python async -# Waits for either confirmation dialog or load spinner. -await page.locator("//span[contains(@class, 'spinner__loading')]|//div[@id='confirmation']").wait_for() -``` - -```python sync -# Waits for either confirmation dialog or load spinner. -page.locator("//span[contains(@class, 'spinner__loading')]|//div[@id='confirmation']").wait_for() -``` - -```csharp -// Waits for either confirmation dialog or load spinner. -await page.Locator("//span[contains(@class, 'spinner__loading')]|//div[@id='confirmation']").WaitFor(); -``` - -## Selecting elements in Shadow DOM - -Our `css` and `text` engines pierce the [Shadow DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM) by default: -- First they search for the elements in the light DOM in the iteration order, and -- Then they search recursively inside open shadow roots in the iteration order. - -In particular, in `css` engine, any [Descendant combinator](https://developer.mozilla.org/en-US/docs/Web/CSS/Descendant_combinator) -or [Child combinator](https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator) pierces an -arbitrary number of open shadow roots, including the implicit descendant combinator at the start of the -selector. It does not search inside closed shadow roots or iframes. - -If you'd like to opt out of this behavior, you can use `:light` CSS extension or `text:light` selector engine. They do not pierce shadow roots. - -```js -await page.locator(':light(.article > .header)').click(); -``` - -```java -page.locator(":light(.article > .header)").click(); -``` - -```python async -await page.locator(":light(.article > .header)").click() -``` - -```python sync -page.locator(":light(.article > .header)").click() -``` - -```csharp -await page.Locator(":light(.article > .header)").ClickAsync(); -``` - -More advanced Shadow DOM use cases: - -```html -
-
In the light dom
-
In the light dom, but goes into the shadow slot
- #shadow-root -
- - In the shadow dom - #shadow-root -
  • Deep in the shadow
  • -
    -
    - -
    -``` - -- Both `"article div"` and `":light(article div)"` match the first `
    In the light dom
    `. -- Both `"article > div"` and `":light(article > div)"` match two `div` elements that are direct children of the `article`. -- `"article .in-the-shadow"` matches the `
    `, piercing the shadow root, while `":light(article .in-the-shadow)"` does not match anything. -- `":light(article div > span)"` does not match anything, because both light-dom `div` elements do not contain a `span`. -- `"article div > span"` matches the ``, piercing the shadow root. -- `"article > .in-the-shadow"` does not match anything, because `
    ` is not a direct child of `article` -- `":light(article > .in-the-shadow)"` does not match anything. -- `"article li#target"` matches the `
  • Deep in the shadow
  • `, piercing two shadow roots. - -## Selecting elements based on layout - -Sometimes, it is hard to come up with a good selector to the target element when it lacks distinctive features. In this case, using Playwright layout selectors could help. These can be combined with regular CSS to pinpoint one of the multiple choices. +Sometimes, it is hard to come up with a good selector to the target element when it lacks distinctive features. In this case, using Playwright layout CSS pseudo-classes could help. These can be combined with regular CSS to pinpoint one of the multiple choices. For example, `input:right-of(:text("Password"))` matches an input field that is to the right of text "Password" - useful when the page has multiple inputs that are hard to distinguish between each other. -Note that layout selector is useful in addition to something else, like `input`. If you use layout selector alone, like `:right-of(:text("Password"))`, most likely you'll get not the input you are looking for, but some empty element in between the text and the target input. +Note that layout pseudo-classes are useful in addition to something else, like `input`. If you use a layout pseudo-class alone, like `:right-of(:text("Password"))`, most likely you'll get not the input you are looking for, but some empty element in between the text and the target input. -:::note -Layout selectors depend on the page layout and may produce unexpected results. For example, a different -element could be matched when layout changes by one pixel. -::: - -Layout selectors use [bounding client rect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) +Layout pseudo-classes use [bounding client rect](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect) to compute distance and relative position of the elements. -* `:right-of(inner > selector)` - Matches elements that are to the right of any element matching the inner selector, at any vertical position. -* `:left-of(inner > selector)` - Matches elements that are to the left of any element matching the inner selector, at any vertical position. -* `:above(inner > selector)` - Matches elements that are above any of the elements matching the inner selector, at any horizontal position. -* `:below(inner > selector)` - Matches elements that are below any of the elements matching the inner selector, at any horizontal position. -* `:near(inner > selector)` - Matches elements that are near (within 50 CSS pixels) any of the elements matching the inner selector. +* `:right-of(div > button)` - Matches elements that are to the right of any element matching the inner selector, at any vertical position. +* `:left-of(div > button)` - Matches elements that are to the left of any element matching the inner selector, at any vertical position. +* `:above(div > button)` - Matches elements that are above any of the elements matching the inner selector, at any horizontal position. +* `:below(div > button)` - Matches elements that are below any of the elements matching the inner selector, at any horizontal position. +* `:near(div > button)` - Matches elements that are near (within 50 CSS pixels) any of the elements matching the inner selector. Note that resulting matches are sorted by their distance to the anchor element, so you can use [`method: Locator.first`] to pick the closest one. This is only useful if you have something like a list of similar elements, where the closest is obviously the right one. However, using [`method: Locator.first`] in other cases most likely won't work as expected - it will not target the element you are searching for, but some other element that happens to be the closest like a random empty `
    `, or an element that is scrolled out and is not currently visible. @@ -572,303 +309,15 @@ await page.Locator("button:near(.promo-card)").ClickAsync(); await page.Locator("[type=radio]:left-of(:text(\"Label 3\"))").First.ClickAsync(); ``` -All layout selectors support optional maximum pixel distance as the last argument. For example -`button:near(:text("Username"), 120)` matches a button that is at most 120 pixels away from the element with the text "Username". +All layout pseudo-classes support optional maximum pixel distance as the last argument. For example +`button:near(:text("Username"), 120)` matches a button that is at most 120 CSS pixels away from the element with the text "Username". -## Selecting elements by label text - -Targeted input actions in Playwright automatically distinguish between labels and controls, so you can target the label to perform an action on the associated control. - -For example, consider the following DOM structure: ``. You can target the label with something like `text=Password` and perform the following actions on the input instead: -- `click` will click the label and automatically focus the input field; -- `fill` will fill the input field; -- `inputValue` will return the value of the input field; -- `selectText` will select text in the input field; -- `setInputFiles` will set files for the input field with `type=file`; -- `selectOption` will select an option from the select box. - -```js -// Fill the input by targeting the label. -await page.locator('text=Password').fill('secret'); -``` - -```java -// Fill the input by targeting the label. -page.locator("text=Password").fill("secret"); -``` - -```python async -# Fill the input by targeting the label. -await page.locator('text=Password').fill('secret') -``` - -```python sync -# Fill the input by targeting the label. -page.locator('text=Password').fill('secret') -``` - -```csharp -// Fill the input by targeting the label. -await page.Locator("text=Password").FillAsync("secret"); -``` - -However, other methods will target the label itself, for example `textContent` will return the text content of the label, not the input field. - -## XPath selectors - -XPath selectors are equivalent to calling [`Document.evaluate`](https://developer.mozilla.org/en/docs/Web/API/Document/evaluate). -Example: `xpath=//html/body`. - -Selector starting with `//` or `..` is assumed to be an xpath selector. For example, Playwright -converts `'//html/body'` to `'xpath=//html/body'`. +### CSS: pick n-th match from the query result :::note -`xpath` does not pierce shadow roots +It is usually possible to distinguish elements by some attribute or text content, which is more resilient to page changes. ::: -## N-th element selector - -You can narrow down query to the n-th match using the `nth=` selector. Unlike CSS's nth-match, provided index is 0-based. - -```js -// Click first button -await page.locator('button >> nth=0').click(); - -// Click last button -await page.locator('button >> nth=-1').click(); -``` - -```java -// Click first button -page.locator("button >> nth=0").click(); - -// Click last button -page.locator("button >> nth=-1").click(); -``` - -```python async -# Click first button -await page.locator("button >> nth=0").click() - -# Click last button -await page.locator("button >> nth=-1").click() -``` - -```python sync -# Click first button -page.locator("button >> nth=0").click() - -# Click last button -page.locator("button >> nth=-1").click() -``` - -```csharp -// Click first button -await page.Locator("button >> nth=0").ClickAsync(); - -// Click last button -await page.Locator("button >> nth=-1").ClickAsync(); -``` - -## React selectors - -:::note -React selectors are experimental and prefixed with `_`. The functionality might change in future. -::: - -React selectors allow selecting elements by their component name and property values. The syntax is very similar to [attribute selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) and supports all attribute selector operators. - -In react selectors, component names are transcribed with **CamelCase**. - -Selector examples: - -- match by **component**: `_react=BookItem` -- match by component and **exact property value**, case-sensitive: `_react=BookItem[author = "Steven King"]` -- match by property value only, **case-insensitive**: `_react=[author = "steven king" i]` -- match by component and **truthy property value**: `_react=MyButton[enabled]` -- match by component and **boolean value**: `_react=MyButton[enabled = false]` -- match by property **value substring**: `_react=[author *= "King"]` -- match by component and **multiple properties**: `_react=BookItem[author *= "king" i][year = 1990]` -- match by **nested** property value: `_react=[some.nested.value = 12]` -- match by component and property value **prefix**: `_react=BookItem[author ^= "Steven"]` -- match by component and property value **suffix**: `_react=BookItem[author $= "Steven"]` -- match by component and **key**: `_react=BookItem[key = '2']` -- match by property value **regex**: `_react=[author = /Steven(\\s+King)?/i]` - - -To find React element names in a tree use [React DevTools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi). - - -:::note -React selectors support React 15 and above. -::: - -:::note -React selectors, as well as [React DevTools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi), only work against **unminified** application builds. -::: - -## Vue selectors - -:::note -Vue selectors are experimental and prefixed with `_`. The functionality might change in future. -::: - -Vue selectors allow selecting elements by their component name and property values. The syntax is very similar to [attribute selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) and supports all attribute selector operators. - -In Vue selectors, component names are transcribed with **kebab-case**. - -Selector examples: - -- match by **component**: `_vue=book-item` -- match by component and **exact property value**, case-sensitive: `_vue=book-item[author = "Steven King"]` -- match by property value only, **case-insensitive**: `_vue=[author = "steven king" i]` -- match by component and **truthy property value**: `_vue=my-button[enabled]` -- match by component and **boolean value**: `_vue=my-button[enabled = false]` -- match by property **value substring**: `_vue=[author *= "King"]` -- match by component and **multiple properties**: `_vue=book-item[author *= "king" i][year = 1990]` -- match by **nested** property value: `_vue=[some.nested.value = 12]` -- match by component and property value **prefix**: `_vue=book-item[author ^= "Steven"]` -- match by component and property value **suffix**: `_vue=book-item[author $= "Steven"]` -- match by property value **regex**: `_vue=[author = /Steven(\\s+King)?/i]` - -To find Vue element names in a tree use [Vue DevTools](https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd?hl=en). - -:::note -Vue selectors support Vue2 and above. -::: - -:::note -Vue selectors, as well as [Vue DevTools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi), only work against **unminified** application builds. -::: - - -## Role selector - -Role selector allows selecting elements by their [ARIA role](https://www.w3.org/TR/wai-aria-1.2/#roles), [ARIA attributes](https://www.w3.org/TR/wai-aria-1.2/#aria-attributes) and [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). Note that role selector **does not replace** accessibility audits and conformance tests, but rather gives early feedback about the ARIA guidelines. - -The syntax is very similar to [CSS attribute selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors). For example, `role=button[name="Click me"][pressed]` selects a pressed button that has accessible name "Click me". - -Note that many html elements have an implicitly [defined role](https://w3c.github.io/html-aam/#html-element-role-mappings) that is recognized by the role selector. You can find all the [supported roles here](https://www.w3.org/TR/wai-aria-1.2/#role_definitions). ARIA guidelines **do not recommend** duplicating implicit roles and attributes by setting `role` and/or `aria-*` attributes to default values. - -Attributes supported by the role selector: -* `checked` - an attribute that is usually set by `aria-checked` or native `` controls. Available values for checked are `true`, `false` and `"mixed"`. Examples: - - `role=checkbox[checked=true]`, equivalent to `role=checkbox[checked]` - - `role=checkbox[checked=false]` - - `role=checkbox[checked="mixed"]` - - Learn more about [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked). - -* `disabled` - a boolean attribute that is usually set by `aria-disabled` or `disabled`. Examples: - - `role=button[disabled=true]`, equivalent to `role=button[disabled]` - - `role=button[disabled=false]` - - Note that unlike most other attributes, `disabled` is inherited through the DOM hierarchy. - Learn more about [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled). - -* `expanded` - a boolean attribute that is usually set by `aria-expanded`. Examples: - - `role=button[expanded=true]`, equivalent to `role=button[expanded]` - - `role=button[expanded=false]` - - Learn more about [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded). - -* `include-hidden` - a boolean attribute that controls whether hidden elements are matched. By default, only non-hidden elements, as [defined by ARIA](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion), are matched by role selector. With `[include-hidden]`, both hidden and non-hidden elements are matched. Examples: - - `role=button[include-hidden=true]`, equivalent to `role=button[include-hidden]` - - `role=button[include-hidden=false]` - - Learn more about [`aria-hidden`](https://www.w3.org/TR/wai-aria-1.2/#aria-hidden). - -* `level` - a number attribute that is usually present for roles `heading`, `listitem`, `row`, `treeitem`, with default values for `

    -

    ` elements. Examples: - - `role=heading[level=1]` - - Learn more about [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level). - -* `name` - a string attribute that matches [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). Supports attribute operators like `=` and `*=`, and regular expressions. - - `role=button[name="Click me"]` - - `role=button[name*="Click"]` - - `role=button[name=/Click( me)?/]` - - Learn more about [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). - -* `pressed` - an attribute that is usually set by `aria-pressed`. Available values for pressed are `true`, `false` and `"mixed"`. Examples: - - `role=button[pressed=true]`, equivalent to `role=button[pressed]` - - `role=button[pressed=false]` - - `role=button[pressed="mixed"]` - - Learn more about [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed). - -* `selected` - a boolean attribute that is usually set by `aria-selected`. Examples: - - `role=option[selected=true]`, equivalent to `role=option[selected]` - - `role=option[selected=false]` - - Learn more about [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected). - -Examples: -* `role=button` matches all buttons; -* `role=button[name="Click me"]` matches buttons with "Click me" accessible name; -* `role=checkbox[checked][include-hidden]` matches checkboxes that are checked, including those that are currently hidden. - - -## id, data-testid, data-test-id, data-test selectors - -Playwright supports shorthand for selecting elements using certain attributes. Currently, only -the following attributes are supported: - -- `id` -- `data-testid` -- `data-test-id` -- `data-test` - -```js -// Fill an input with the id "username" -await page.locator('id=username').fill('value'); - -// Click an element with data-test-id "submit" -await page.locator('data-test-id=submit').click(); -``` - -```java -// Fill an input with the id "username" -page.locator("id=username").fill("value"); - -// Click an element with data-test-id "submit" -page.locator("data-test-id=submit").click(); -``` - -```python async -# Fill an input with the id "username" -await page.locator('id=username').fill('value') - -# Click an element with data-test-id "submit" -await page.locator('data-test-id=submit').click() -``` - -```python sync -# Fill an input with the id "username" -page.locator('id=username').fill('value') - -# Click an element with data-test-id "submit" -page.locator('data-test-id=submit').click() -``` - -```csharp -// Fill an input with the id "username" -await page.Locator("id=username").FillAsync("value"); - -// Click an element with data-test-id "submit" -await page.Locator("data-test-id=submit").ClickAsync(); -``` - -:::note -Attribute selectors are not CSS selectors, so anything CSS-specific like `:enabled` is not supported. For more features, use a proper [css] selector, e.g. `css=[data-test="login"]:enabled`. -::: - -:::note -Attribute selectors pierce shadow DOM. To opt-out from this behavior, use `:light` suffix after attribute, for example `page.locator('data-test-id:light=submit').click()` -::: - - -## Pick n-th match from the query result - Sometimes page contains a number of similar elements, and it is hard to select a particular one. For example: ```html @@ -935,39 +384,536 @@ await page.Locator(":nth-match(:text('Buy'), 3)").WaitForAsync(); Unlike [`:nth-child()`](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child), elements do not have to be siblings, they could be anywhere on the page. In the snippet above, all three buttons match `:text("Buy")` selector, and `:nth-match()` selects the third button. ::: -:::note -It is usually possible to distinguish elements by some attribute or text content. In this case, -prefer using [text] or [css] selectors over the `:nth-match()`. -::: -## Parent selector +## N-th element locator -The parent could be selected with `..`, which is a short form for `xpath=..`. +You can narrow down query to the n-th match using the `nth=` locator passing a zero-based index. + +```js +// Click first button +await page.locator('button').locator('nth=0').click(); + +// Click last button +await page.locator('button').locator('nth=-1').click(); +``` + +```java +// Click first button +page.locator("button").locator("nth=0").click(); + +// Click last button +page.locator("button").locator("nth=-1").click(); +``` + +```python async +# Click first button +await page.locator("button").locator("nth=0").click() + +# Click last button +await page.locator("button").locator("nth=-1").click() +``` + +```python sync +# Click first button +page.locator("button").locator("nth=0").click() + +# Click last button +page.locator("button").locator("nth=-1").click() +``` + +```csharp +// Click first button +await page.Locator("button").Locator("nth=0").ClickAsync(); + +// Click last button +await page.Locator("button").Locator("nth=-1").ClickAsync(); +``` + + +## Parent element locator + +The parent element could be selected with `..`, which is a short form for `xpath=..`. For example: ```js -const parentLocator = elementLocator.locator('..'); +const parentLocator = page.getByRole('button').locator('..'); ``` ```java -Locator parentLocator = elementLocator.locator(".."); +Locator parentLocator = page.getByRole(AriaRole.BUTTON).locator(".."); ``` ```python async -parent_locator = element_locator.locator('..') +parent_locator = page.get_by_role("button").locator('..') ``` ```python sync -parent_locator = element_locator.locator('..') +parent_locator = page.get_by_role("button").locator('..') ``` ```csharp -var parentLocator = elementLocator.Locator(".."); +var parentLocator = page.GetByRole(AriaRole.Button).Locator(".."); ``` + +### Locating only visible elements + +:::note +It's usually better to find a [more reliable way](./locators.md#quick-guide) to uniquely identify the element instead of checking the visibility. +::: + +Consider a page with two buttons, first invisible and second [visible](./actionability.md#visible). + +```html + + +``` + +* This will find both buttons and throw a [strictness](./locators.md#strictness) violation error: + + ```js + await page.locator('button').click(); + ``` + + ```java + page.locator("button").click(); + ``` + + ```python async + await page.locator("button").click() + ``` + + ```python sync + page.locator("button").click() + ``` + + ```csharp + await page.Locator("button").ClickAsync(); + ``` + +* This will only find a second button, because it is visible, and then click it. + + ```js + await page.locator('button').locator('visible=true').click(); + ``` + ```java + page.locator("button").locator("visible=true").click(); + ``` + ```python async + await page.locator("button").locator("visible=true").click() + ``` + ```python sync + page.locator("button").locator("visible=true").click() + ``` + ```csharp + await page.Locator("button").Locator("visible=true").ClickAsync(); + ``` + + +## React locator + +:::note +React locator is experimental and prefixed with `_`. The functionality might change in future. +::: + +React locator allows finding elements by their component name and property values. The syntax is very similar to [CSS attribute selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) and supports all CSS attribute selector operators. + +In React locator, component names are transcribed with **CamelCase**. + +```js +await page.locator('_react=BookItem').click(); +``` +```java +page.locator("_react=BookItem").click(); +``` +```python async +await page.locator("_react=BookItem").click() +``` +```python sync +page.locator("_react=BookItem").click() +``` +```csharp +await page.Locator("_react=BookItem").ClickAsync(); +``` + +More examples: + +- match by **component**: `_react=BookItem` +- match by component and **exact property value**, case-sensitive: `_react=BookItem[author = "Steven King"]` +- match by property value only, **case-insensitive**: `_react=[author = "steven king" i]` +- match by component and **truthy property value**: `_react=MyButton[enabled]` +- match by component and **boolean value**: `_react=MyButton[enabled = false]` +- match by property **value substring**: `_react=[author *= "King"]` +- match by component and **multiple properties**: `_react=BookItem[author *= "king" i][year = 1990]` +- match by **nested** property value: `_react=[some.nested.value = 12]` +- match by component and property value **prefix**: `_react=BookItem[author ^= "Steven"]` +- match by component and property value **suffix**: `_react=BookItem[author $= "Steven"]` +- match by component and **key**: `_react=BookItem[key = '2']` +- match by property value **regex**: `_react=[author = /Steven(\\s+King)?/i]` + + +To find React element names in a tree use [React DevTools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi). + + +:::note +React locator supports React 15 and above. +::: + +:::note +React locator, as well as [React DevTools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi), only work against **unminified** application builds. +::: + +## Vue locator + +:::note +Vue locator is experimental and prefixed with `_`. The functionality might change in future. +::: + +Vue locator allows finding elements by their component name and property values. The syntax is very similar to [CSS attribute selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) and supports all CSS attribute selector operators. + +In Vue locator, component names are transcribed with **kebab-case**. + +```js +await page.locator('_vue=book-item').click(); +``` +```java +page.locator("_vue=book-item").click(); +``` +```python async +await page.locator("_vue=book-item").click() +``` +```python sync +page.locator("_vue=book-item").click() +``` +```csharp +await page.Locator("_vue=book-item").ClickAsync(); +``` + +More examples: + +- match by **component**: `_vue=book-item` +- match by component and **exact property value**, case-sensitive: `_vue=book-item[author = "Steven King"]` +- match by property value only, **case-insensitive**: `_vue=[author = "steven king" i]` +- match by component and **truthy property value**: `_vue=my-button[enabled]` +- match by component and **boolean value**: `_vue=my-button[enabled = false]` +- match by property **value substring**: `_vue=[author *= "King"]` +- match by component and **multiple properties**: `_vue=book-item[author *= "king" i][year = 1990]` +- match by **nested** property value: `_vue=[some.nested.value = 12]` +- match by component and property value **prefix**: `_vue=book-item[author ^= "Steven"]` +- match by component and property value **suffix**: `_vue=book-item[author $= "Steven"]` +- match by property value **regex**: `_vue=[author = /Steven(\\s+King)?/i]` + +To find Vue element names in a tree use [Vue DevTools](https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd?hl=en). + +:::note +Vue locator supports Vue2 and above. +::: + +:::note +Vue locator, as well as [Vue DevTools](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi), only work against **unminified** application builds. +::: + + +## XPath locator + +:::warning +We recommend prioritzing [user-visible locators](./locators.md#quick-guide) like text or accessible role instead of using XPath that is tied to the implementation and easily break when the page changes. +::: + +XPath locators are equivalent to calling [`Document.evaluate`](https://developer.mozilla.org/en/docs/Web/API/Document/evaluate). + +```js +await page.locator('xpath=//button').click(); +``` +```java +page.locator("xpath=//button").click(); +``` +```python async +await page.locator("xpath=//button").click() +``` +```python sync +page.locator("xpath=//button").click() +``` +```csharp +await page.Locator("xpath=//button").ClickAsync(); +``` + +:::note +Any selector string starting with `//` or `..` are assumed to be an xpath selector. For example, Playwright converts `'//html/body'` to `'xpath=//html/body'`. +::: + +:::note +XPath does not pierce shadow roots. +::: + + +### XPath union + +Pipe operator (`|`) can be used to specify multiple selectors in XPath. It will match all +elements that can be selected by one of the selectors in that list. + +```js +// Waits for either confirmation dialog or load spinner. +await page.locator(`//span[contains(@class, 'spinner__loading')]|//div[@id='confirmation']`).waitFor(); +``` + +```java +// Waits for either confirmation dialog or load spinner. +page.locator("//span[contains(@class, 'spinner__loading')]|//div[@id='confirmation']").waitFor(); +``` + +```python async +# Waits for either confirmation dialog or load spinner. +await page.locator("//span[contains(@class, 'spinner__loading')]|//div[@id='confirmation']").wait_for() +``` + +```python sync +# Waits for either confirmation dialog or load spinner. +page.locator("//span[contains(@class, 'spinner__loading')]|//div[@id='confirmation']").wait_for() +``` + +```csharp +// Waits for either confirmation dialog or load spinner. +await page.Locator("//span[contains(@class, 'spinner__loading')]|//div[@id='confirmation']").WaitForAsync(); +``` + + +## Label to form control retargeting + +:::warning +We recommend [locating by label text](./locators.md#locate-by-label) instead of relying to label-to-control retargeting. +::: + +Targeted input actions in Playwright automatically distinguish between labels and controls, so you can target the label to perform an action on the associated control. + +For example, consider the following DOM structure: ``. You can target the label by it's "Password" text using [`method: Page.getByText`]. However, the following actions will be performed on the input instead of the label: +- [`method: Locator.click`] will click the label and automatically focus the input field; +- [`method: Locator.fill`] will fill the input field; +- [`method: Locator.inputValue`] will return the value of the input field; +- [`method: Locator.selectText`] will select text in the input field; +- [`method: Locator.setInputFiles`] will set files for the input field with `type=file`; +- [`method: Locator.selectOption`] will select an option from the select box. + +```js +// Fill the input by targeting the label. +await page.getByText('Password').fill('secret'); +``` + +```java +// Fill the input by targeting the label. +page.getByText("Password").fill("secret"); +``` + +```python async +# Fill the input by targeting the label. +await page.get_by_text("Password").fill("secret") +``` + +```python sync +# Fill the input by targeting the label. +page.get_by_text("Password").fill("secret") +``` + +```csharp +// Fill the input by targeting the label. +await page.GetByText("Password").FillAsync("secret"); +``` + +However, other methods will target the label itself, for example [`method: LocatorAssertions.toHaveText`] will assert the text content of the label, not the input field. + + +```js +// Fill the input by targeting the label. +await expect(page.locator('label')).toHaveText('Password'); +``` + +```java +// Fill the input by targeting the label. +assertThat(page.locator("label")).hasText("Password"); +``` + +```python async +# Fill the input by targeting the label. +await expect(page.locator("label")).to_have_text("Password") +``` + +```python sync +# Fill the input by targeting the label. +expect(page.locator("label")).to_have_text("Password") +``` + +```csharp +// Fill the input by targeting the label. +await Expect(page.Locator("label")).ToHaveTextAsync("Password"); +``` + +## Legacy text locator + +:::warning +We recommend the modern [text locator](./locators.md#get-by-text) instead. +::: + +Legacy text locator matches elements that contain passed text. + +```js +await page.locator('text=Log in').click(); +``` +```java +page.locator("text=Log in").click(); +``` +```python async +await page.locator("text=Log in").click() +``` +```python sync +page.locator("text=Log in").click() +``` +```csharp +await page.Locator("text=Log in").ClickAsync(); +``` + +Legacy text locator has a few variations: + +- `text=Log in` - default matching is case-insensitive, trims whitespace and searches for a substring. For example, `text=Log` matches ``. + + ```js + await page.locator('text=Log in').click(); + ``` + ```java + page.locator("text=Log in").click(); + ``` + ```python async + await page.locator("text=Log in").click() + ``` + ```python sync + page.locator("text=Log in").click() + ``` + ```csharp + await page.Locator("text=Log in").ClickAsync(); + ``` + +- `text="Log in"` - text body can be escaped with single or double quotes to search for a text node with exact content after trimming whitespace. + + For example, `text="Log"` does not match `` because ``, because ``. + + Quoted body follows the usual escaping rules, e.g. use `\"` to escape double quote in a double-quoted string: `text="foo\"bar"`. + + ```js + await page.locator('text="Log in"').click(); + ``` + ```java + page.locator("text='Log in'").click(); + ``` + ```python async + await page.locator("text='Log in'").click() + ``` + ```python sync + page.locator("text='Log in'").click() + ``` + ```csharp + await page.Locator("text='Log in'").ClickAsync(); + ``` + +- `/Log\s*in/i` - body can be a [JavaScript-like regex](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) wrapped in `/` symbols. For example, `text=/Log\s*in/i` matches `` and ``. + + ```js + await page.locator('text=/Log\\s*in/i').click(); + ``` + ```java + page.locator("text=/Log\\s*in/i").click(); + ``` + ```python async + await page.locator("text=/Log\s*in/i").click() + ``` + ```python sync + page.locator("text=/Log\s*in/i").click() + ``` + ```csharp + await page.Locator("text=/Log\\s*in/i").ClickAsync(); + ``` + +:::note +String selectors starting and ending with a quote (either `"` or `'`) are assumed to be a legacy text locators. For example, `"Log in"` is converted to `text="Log in"` internally. +::: + +:::note +Matching always normalizes whitespace. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace. +::: + +:::note +Input elements of the type `button` and `submit` are matched by their `value` instead of text content. For example, `text=Log in` matches ``. +::: + + +## id, data-testid, data-test-id, data-test selectors + +:::warning +We recommend [locating by test id](./locators.md#locate-by-test-id) instead. +::: + +Playwright supports shorthand for selecting elements using certain attributes. Currently, only +the following attributes are supported: + +- `id` +- `data-testid` +- `data-test-id` +- `data-test` + +```js +// Fill an input with the id "username" +await page.locator('id=username').fill('value'); + +// Click an element with data-test-id "submit" +await page.locator('data-test-id=submit').click(); +``` + +```java +// Fill an input with the id "username" +page.locator("id=username").fill("value"); + +// Click an element with data-test-id "submit" +page.locator("data-test-id=submit").click(); +``` + +```python async +# Fill an input with the id "username" +await page.locator('id=username').fill('value') + +# Click an element with data-test-id "submit" +await page.locator('data-test-id=submit').click() +``` + +```python sync +# Fill an input with the id "username" +page.locator('id=username').fill('value') + +# Click an element with data-test-id "submit" +page.locator('data-test-id=submit').click() +``` + +```csharp +// Fill an input with the id "username" +await page.Locator("id=username").FillAsync("value"); + +// Click an element with data-test-id "submit" +await page.Locator("data-test-id=submit").ClickAsync(); +``` + +:::note +Attribute selectors are not CSS selectors, so anything CSS-specific like `:enabled` is not supported. For more features, use a proper [css] selector, e.g. `css=[data-test="login"]:enabled`. +::: + +:::note +Attribute selectors pierce shadow DOM. To opt-out from this behavior, use `:light` suffix after attribute, for example `page.locator('data-test-id:light=submit').click()` +::: + + ## Chaining selectors +:::warning +We recommend [chaining locators](./locators.md#chaining-locators) instead. +::: + Selectors defined as `engine=body` or in short-form can be combined with the `>>` token, e.g. `selector1 >> selector2 >> selectors3`. When selectors are chained, the next one is queried relative to the previous one's result. For example, @@ -987,6 +933,10 @@ If a selector needs to include `>>` in the body, it should be escaped inside a s ### Intermediate matches +:::warning +We recommend [filtering by another locator](./locators.md#filter-by-another-locator) to locate elements that contain other elements. +::: + By default, chained selectors resolve to an element queried by the last selector. A selector can be prefixed with `*` to capture elements that are queried by an intermediate selector. For example, `css=article >> text=Hello` captures the element with the text `Hello`, and `*css=article >> text=Hello` (note the `*`) captures the `article` element that contains some element with the text `Hello`. diff --git a/docs/src/protractor-js.md b/docs/src/protractor-js.md index 7beb2913c7..16707900b9 100644 --- a/docs/src/protractor-js.md +++ b/docs/src/protractor-js.md @@ -162,8 +162,7 @@ Learn more about Playwright Test runner: - [Getting Started](./intro) - [Fixtures](./test-fixtures) -- [Locators](./api/class-locator) -- [Selectors](./selectors) +- [Locators](./locators) - [Assertions](./test-assertions) - [Auto-waiting](./actionability) diff --git a/docs/src/puppeteer-js.md b/docs/src/puppeteer-js.md index a03f0d278d..9ec95b063d 100644 --- a/docs/src/puppeteer-js.md +++ b/docs/src/puppeteer-js.md @@ -172,7 +172,6 @@ Learn more about Playwright Test runner: - [Getting Started](./intro) - [Fixtures](./test-fixtures) -- [Locators](./api/class-locator) -- [Selectors](./selectors) +- [Locators](./locators.md) - [Assertions](./test-assertions) - [Auto-waiting](./actionability) diff --git a/docs/src/release-notes-csharp.md b/docs/src/release-notes-csharp.md index 93515af0ee..9f9aad235b 100644 --- a/docs/src/release-notes-csharp.md +++ b/docs/src/release-notes-csharp.md @@ -317,7 +317,7 @@ Note that the new methods [`method: Page.routeFromHAR`] and [`method: BrowserCon await page.Locator("role=button[name='log in']").ClickAsync(); ``` - Read more in [our documentation](./selectors#role-selector). + Read more in [our documentation](./locators.md#locate-by-role). - New [`method: Locator.filter`] API to filter an existing locator @@ -339,7 +339,7 @@ Note that the new methods [`method: Page.routeFromHAR`] and [`method: BrowserCon await page.Locator("role=button[name='log in']").ClickAsync(); ``` - Read more in [our documentation](./selectors#role-selector). + Read more in [our documentation](./locators.md#locate-by-role). - New `scale` option in [`method: Page.screenshot`] for smaller sized screenshots. - New `caret` option in [`method: Page.screenshot`] to control text caret. Defaults to `"hide"`. - We now ship a designated .NET docker image `mcr.microsoft.com/playwright/dotnet`. Read more in [our documentation](./docker). @@ -628,7 +628,7 @@ await locator.ClickAsync(); Learn more in the [documentation](./api/class-locator). -#### 🧩 Experimental [**React**](./selectors#react-selectors) and [**Vue**](./selectors#vue-selectors) selector engines +#### 🧩 Experimental [**React**](./other-locators.md#react-locator) and [**Vue**](./other-locators.md#vue-locator) selector engines React and Vue selectors allow selecting elements by its component name and/or property values. The syntax is very similar to [attribute selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) and supports all attribute selector operators. @@ -637,12 +637,12 @@ await page.Locator("_react=SubmitButton[enabled=true]").ClickAsync(); await page.Locator("_vue=submit-button[enabled=true]").ClickAsync(); ``` -Learn more in the [react selectors documentation](./selectors#react-selectors) and the [vue selectors documentation](./selectors#vue-selectors). +Learn more in the [react selectors documentation](./other-locators.md#react-locator) and the [vue selectors documentation](./other-locators.md#vue-locator). -#### ✨ New [**`nth`**](./selectors#n-th-element-selector) and [**`visible`**](./selectors#selecting-visible-elements) selector engines +#### ✨ New [**`nth`**](./other-locators.md#n-th-element-locator) and [**`visible`**](./other-locators.md#css-matching-only-visible-elements) selector engines -- [`nth`](./selectors#n-th-element-selector) selector engine is equivalent to the `:nth-match` pseudo class, but could be combined with other selector engines. -- [`visible`](./selectors#selecting-visible-elements) selector engine is equivalent to the `:visible` pseudo class, but could be combined with other selector engines. +- [`nth`](./other-locators.md#n-th-element-locator) selector engine is equivalent to the `:nth-match` pseudo class, but could be combined with other selector engines. +- [`visible`](./other-locators.md#css-matching-only-visible-elements) selector engine is equivalent to the `:visible` pseudo class, but could be combined with other selector engines. ```csharp // select the first button among all buttons diff --git a/docs/src/release-notes-java.md b/docs/src/release-notes-java.md index 5025f2bf7b..84e1c42917 100644 --- a/docs/src/release-notes-java.md +++ b/docs/src/release-notes-java.md @@ -257,7 +257,7 @@ Note that the new methods [`method: Page.routeFromHAR`] and [`method: BrowserCon page.locator("role=button[name='log in']").click(); ``` - Read more in [our documentation](./selectors#role-selector). + Read more in [our documentation](./locators.md#locate-by-role). - New [`method: Locator.filter`] API to filter an existing locator @@ -283,7 +283,7 @@ Note that the new methods [`method: Page.routeFromHAR`] and [`method: BrowserCon page.locator("role=button[name='log in']").click(); ``` - Read more in [our documentation](./selectors#role-selector). + Read more in [our documentation](./locators.md#locate-by-role). - New `scale` option in [`method: Page.screenshot`] for smaller sized screenshots. - New `caret` option in [`method: Page.screenshot`] to control text caret. Defaults to `"hide"`. @@ -590,7 +590,7 @@ locator.click(); Learn more in the [documentation](./api/class-locator). -#### 🧩 Experimental [**React**](./selectors#react-selectors) and [**Vue**](./selectors#vue-selectors) selector engines +#### 🧩 Experimental [**React**](./other-locators.md#react-locator) and [**Vue**](./other-locators.md#vue-locator) selector engines React and Vue selectors allow selecting elements by its component name and/or property values. The syntax is very similar to [attribute selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) and supports all attribute selector operators. @@ -599,12 +599,12 @@ page.locator("_react=SubmitButton[enabled=true]").click(); page.locator("_vue=submit-button[enabled=true]").click(); ``` -Learn more in the [react selectors documentation](./selectors#react-selectors) and the [vue selectors documentation](./selectors#vue-selectors). +Learn more in the [react selectors documentation](./other-locators.md#react-locator) and the [vue selectors documentation](./other-locators.md#vue-locator). -#### ✨ New [**`nth`**](./selectors#n-th-element-selector) and [**`visible`**](./selectors#selecting-visible-elements) selector engines +#### ✨ New [**`nth`**](./other-locators.md#n-th-element-locator) and [**`visible`**](./other-locators.md#css-matching-only-visible-elements) selector engines -- [`nth`](./selectors#n-th-element-selector) selector engine is equivalent to the `:nth-match` pseudo class, but could be combined with other selector engines. -- [`visible`](./selectors#selecting-visible-elements) selector engine is equivalent to the `:visible` pseudo class, but could be combined with other selector engines. +- [`nth`](./other-locators.md#n-th-element-locator) selector engine is equivalent to the `:nth-match` pseudo class, but could be combined with other selector engines. +- [`visible`](./other-locators.md#css-matching-only-visible-elements) selector engine is equivalent to the `:visible` pseudo class, but could be combined with other selector engines. ```java // select the first button among all buttons @@ -777,7 +777,7 @@ This version of Playwright was also tested against the following stable channels - **Pause script execution** with [`method: Page.pause`] in headed mode. Pausing the page launches [Playwright Inspector](./debug.md) for debugging. -- **New has-text pseudo-class** for CSS selectors. `:has-text("example")` matches any element containing `"example"` somewhere inside, possibly in a child or a descendant element. See [more examples](./selectors.md#text-selector). +- **New has-text pseudo-class** for CSS selectors. `:has-text("example")` matches any element containing `"example"` somewhere inside, possibly in a child or a descendant element. See [more examples](./other-locators.md#css-matching-by-text). - **Page dialogs are now auto-dismissed** during execution, unless a listener for `dialog` event is configured. [Learn more](./dialogs.md) about this. @@ -795,7 +795,7 @@ This version of Playwright was also tested against the following stable channels ## Version 1.8 -- [Selecting elements based on layout](./selectors.md#selecting-elements-based-on-layout) with `:left-of()`, `:right-of()`, `:above()` and `:below()`. +- [Selecting elements based on layout](./other-locators.md#css-matching-elements-based-on-layout) with `:left-of()`, `:right-of()`, `:above()` and `:below()`. - Playwright now includes [command line interface](./cli.md), former playwright-cli. ```bash java mvn exec:java -e -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args="--help" @@ -829,7 +829,7 @@ This version of Playwright was also tested against the following stable channels - **New Java SDK**: [Playwright for Java](https://github.com/microsoft/playwright-java) is now on par with [JavaScript](https://github.com/microsoft/playwright), [Python](https://github.com/microsoft/playwright-python) and [.NET bindings](https://github.com/microsoft/playwright-dotnet). - **Browser storage API**: New convenience APIs to save and load browser storage state (cookies, local storage) to simplify automation scenarios with authentication. -- **New CSS selectors**: We heard your feedback for more flexible selectors and have revamped the selectors implementation. Playwright 1.7 introduces [new CSS extensions](./selectors.md) and there's more coming soon. +- **New CSS selectors**: We heard your feedback for more flexible selectors and have revamped the selectors implementation. Playwright 1.7 introduces [new CSS extensions](./other-locators.md#css-locator) and there's more coming soon. - **New website**: The docs website at [playwright.dev](https://playwright.dev/) has been updated and is now built with [Docusaurus](https://v2.docusaurus.io/). - **Support for Apple Silicon**: Playwright browser binaries for WebKit and Chromium are now built for Apple Silicon. diff --git a/docs/src/release-notes-js.md b/docs/src/release-notes-js.md index e03e67b82c..1803f1f72c 100644 --- a/docs/src/release-notes-js.md +++ b/docs/src/release-notes-js.md @@ -526,7 +526,7 @@ WebServer is now considered "ready" if request to the specified port has any of await page.locator('role=button[name="log in"]').click() ``` - Read more in [our documentation](./selectors#role-selector). + Read more in [our documentation](./locators.md#locate-by-role). - New [`method: Locator.filter`] API to filter an existing locator @@ -568,7 +568,7 @@ WebServer is now considered "ready" if request to the specified port has any of await page.locator('role=button[name="log in"]').click() ``` - Read more in [our documentation](./selectors#role-selector). + Read more in [our documentation](./locators.md#locate-by-role). - New `scale` option in [`method: Page.screenshot`] for smaller sized screenshots. - New `caret` option in [`method: Page.screenshot`] to control text caret. Defaults to `"hide"`. @@ -1160,7 +1160,7 @@ await locator.click(); Learn more in the [documentation](./api/class-locator). -#### 🧩 Experimental [**React**](./selectors#react-selectors) and [**Vue**](./selectors#vue-selectors) selector engines +#### 🧩 Experimental [**React**](./other-locators.md#react-locator) and [**Vue**](./other-locators.md#vue-locator) selector engines React and Vue selectors allow selecting elements by its component name and/or property values. The syntax is very similar to [attribute selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) and supports all attribute selector operators. @@ -1169,12 +1169,12 @@ await page.locator('_react=SubmitButton[enabled=true]').click(); await page.locator('_vue=submit-button[enabled=true]').click(); ``` -Learn more in the [react selectors documentation](./selectors#react-selectors) and the [vue selectors documentation](./selectors#vue-selectors). +Learn more in the [react selectors documentation](./other-locators.md#react-locator) and the [vue selectors documentation](./other-locators.md#vue-locator). -#### ✨ New [**`nth`**](./selectors#n-th-element-selector) and [**`visible`**](./selectors#selecting-visible-elements) selector engines +#### ✨ New [**`nth`**](./other-locators.md#n-th-element-locator) and [**`visible`**](./other-locators.md#css-matching-only-visible-elements) selector engines -- [`nth`](./selectors#n-th-element-selector) selector engine is equivalent to the `:nth-match` pseudo class, but could be combined with other selector engines. -- [`visible`](./selectors#selecting-visible-elements) selector engine is equivalent to the `:visible` pseudo class, but could be combined with other selector engines. +- [`nth`](./other-locators.md#n-th-element-locator) selector engine is equivalent to the `:nth-match` pseudo class, but could be combined with other selector engines. +- [`visible`](./other-locators.md#css-matching-only-visible-elements) selector engine is equivalent to the `:visible` pseudo class, but could be combined with other selector engines. ```js // select the first button among all buttons @@ -1481,7 +1481,7 @@ This version of Playwright was also tested against the following stable channels - **Pause script execution** with [`method: Page.pause`] in headed mode. Pausing the page launches [Playwright Inspector](./debug.md) for debugging. -- **New has-text pseudo-class** for CSS selectors. `:has-text("example")` matches any element containing `"example"` somewhere inside, possibly in a child or a descendant element. See [more examples](./selectors.md#text-selector). +- **New has-text pseudo-class** for CSS selectors. `:has-text("example")` matches any element containing `"example"` somewhere inside, possibly in a child or a descendant element. See [more examples](./other-locators.md#css-matching-by-text). - **Page dialogs are now auto-dismissed** during execution, unless a listener for `dialog` event is configured. [Learn more](./dialogs.md) about this. @@ -1499,7 +1499,7 @@ This version of Playwright was also tested against the following stable channels ## Version 1.8 -- [Selecting elements based on layout](./selectors.md#selecting-elements-based-on-layout) with `:left-of()`, `:right-of()`, `:above()` and `:below()`. +- [Selecting elements based on layout](./other-locators.md#css-matching-elements-based-on-layout) with `:left-of()`, `:right-of()`, `:above()` and `:below()`. - Playwright now includes [command line interface](./cli.md), former playwright-cli. ```bash js npx playwright --help @@ -1533,7 +1533,7 @@ This version of Playwright was also tested against the following stable channels - **New Java SDK**: [Playwright for Java](https://github.com/microsoft/playwright-java) is now on par with [JavaScript](https://github.com/microsoft/playwright), [Python](https://github.com/microsoft/playwright-python) and [.NET bindings](https://github.com/microsoft/playwright-dotnet). - **Browser storage API**: New convenience APIs to save and load browser storage state (cookies, local storage) to simplify automation scenarios with authentication. -- **New CSS selectors**: We heard your feedback for more flexible selectors and have revamped the selectors implementation. Playwright 1.7 introduces [new CSS extensions](./selectors.md) and there's more coming soon. +- **New CSS selectors**: We heard your feedback for more flexible selectors and have revamped the selectors implementation. Playwright 1.7 introduces [new CSS extensions](./other-locators.md#css-locator) and there's more coming soon. - **New website**: The docs website at [playwright.dev](https://playwright.dev/) has been updated and is now built with [Docusaurus](https://v2.docusaurus.io/). - **Support for Apple Silicon**: Playwright browser binaries for WebKit and Chromium are now built for Apple Silicon. diff --git a/docs/src/release-notes-python.md b/docs/src/release-notes-python.md index d41874413b..a3c3bbcc91 100644 --- a/docs/src/release-notes-python.md +++ b/docs/src/release-notes-python.md @@ -302,7 +302,7 @@ Note that the new methods [`method: Page.routeFromHAR`] and [`method: BrowserCon page.locator("role=button[name='log in']").click() ``` - Read more in [our documentation](./selectors#role-selector). + Read more in [our documentation](./locators.md#locate-by-role). - New [`method: Locator.filter`] API to filter an existing locator @@ -335,7 +335,7 @@ Note that the new methods [`method: Page.routeFromHAR`] and [`method: BrowserCon page.locator("role=button[name='log in']").click() ``` - Read more in [our documentation](./selectors#role-selector). + Read more in [our documentation](./locators.md#locate-by-role). - New `scale` option in [`method: Page.screenshot`] for smaller sized screenshots. - New `caret` option in [`method: Page.screenshot`] to control text caret. Defaults to `"hide"`. @@ -663,7 +663,7 @@ locator.click() Learn more in the [documentation](./api/class-locator). -#### 🧩 Experimental [**React**](./selectors#react-selectors) and [**Vue**](./selectors#vue-selectors) selector engines +#### 🧩 Experimental [**React**](./other-locators.md#react-locator) and [**Vue**](./other-locators.md#vue-locator) selector engines React and Vue selectors allow selecting elements by its component name and/or property values. The syntax is very similar to [attribute selectors](https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors) and supports all attribute selector operators. @@ -672,12 +672,12 @@ page.locator("_react=SubmitButton[enabled=true]").click() page.locator("_vue=submit-button[enabled=true]").click() ``` -Learn more in the [react selectors documentation](./selectors#react-selectors) and the [vue selectors documentation](./selectors#vue-selectors). +Learn more in the [react selectors documentation](./other-locators.md#react-locator) and the [vue selectors documentation](./other-locators.md#vue-locator). -#### ✨ New [**`nth`**](./selectors#n-th-element-selector) and [**`visible`**](./selectors#selecting-visible-elements) selector engines +#### ✨ New [**`nth`**](./other-locators.md#n-th-element-locator) and [**`visible`**](./other-locators.md#css-matching-only-visible-elements) selector engines -- [`nth`](./selectors#n-th-element-selector) selector engine is equivalent to the `:nth-match` pseudo class, but could be combined with other selector engines. -- [`visible`](./selectors#selecting-visible-elements) selector engine is equivalent to the `:visible` pseudo class, but could be combined with other selector engines. +- [`nth`](./other-locators.md#n-th-element-locator) selector engine is equivalent to the `:nth-match` pseudo class, but could be combined with other selector engines. +- [`visible`](./other-locators.md#css-matching-only-visible-elements) selector engine is equivalent to the `:visible` pseudo class, but could be combined with other selector engines. ```py # select the first button among all buttons @@ -848,7 +848,7 @@ This version of Playwright was also tested against the following stable channels - **Pause script execution** with [`method: Page.pause`] in headed mode. Pausing the page launches [Playwright Inspector](./debug.md) for debugging. -- **New has-text pseudo-class** for CSS selectors. `:has-text("example")` matches any element containing `"example"` somewhere inside, possibly in a child or a descendant element. See [more examples](./selectors.md#text-selector). +- **New has-text pseudo-class** for CSS selectors. `:has-text("example")` matches any element containing `"example"` somewhere inside, possibly in a child or a descendant element. See [more examples](./other-locators.md#css-matching-by-text). - **Page dialogs are now auto-dismissed** during execution, unless a listener for `dialog` event is configured. [Learn more](./dialogs.md) about this. @@ -866,7 +866,7 @@ This version of Playwright was also tested against the following stable channels ## Version 1.8 -- [Selecting elements based on layout](./selectors.md#selecting-elements-based-on-layout) with `:left-of()`, `:right-of()`, `:above()` and `:below()`. +- [Selecting elements based on layout](./other-locators.md#css-matching-elements-based-on-layout) with `:left-of()`, `:right-of()`, `:above()` and `:below()`. - Playwright now includes [command line interface](./cli.md), former playwright-cli. ```bash python playwright --help @@ -900,7 +900,7 @@ This version of Playwright was also tested against the following stable channels - **New Java SDK**: [Playwright for Java](https://github.com/microsoft/playwright-java) is now on par with [JavaScript](https://github.com/microsoft/playwright), [Python](https://github.com/microsoft/playwright-python) and [.NET bindings](https://github.com/microsoft/playwright-dotnet). - **Browser storage API**: New convenience APIs to save and load browser storage state (cookies, local storage) to simplify automation scenarios with authentication. -- **New CSS selectors**: We heard your feedback for more flexible selectors and have revamped the selectors implementation. Playwright 1.7 introduces [new CSS extensions](./selectors.md) and there's more coming soon. +- **New CSS selectors**: We heard your feedback for more flexible selectors and have revamped the selectors implementation. Playwright 1.7 introduces [new CSS extensions](./other-locators.md#css-locator) and there's more coming soon. - **New website**: The docs website at [playwright.dev](https://playwright.dev/) has been updated and is now built with [Docusaurus](https://v2.docusaurus.io/). - **Support for Apple Silicon**: Playwright browser binaries for WebKit and Chromium are now built for Apple Silicon. diff --git a/docs/src/running-tests-csharp.md b/docs/src/running-tests-csharp.md index b5129b2042..4a1c9cf7b6 100644 --- a/docs/src/running-tests-csharp.md +++ b/docs/src/running-tests-csharp.md @@ -36,7 +36,7 @@ You can run a single test, a set of tests or all tests. Tests can be run on diff ``` - Running Tests on multiple browsers - + To run your test on multiple browsers or configurations you need to invoke the `dotnet test` command multiple times. There you can then either specify the `BROWSER` environment variable or set the `Playwright.BrowserName` via the runsettings file: ```bash @@ -58,7 +58,7 @@ For more information see [selective unit tests](https://docs.microsoft.com/en-us ## Debugging Tests -Since Playwright runs in .NET, you can debug it with your debugger of choice in e.g. Visual Studio Code or Visual Studio. Playwright comes with the Playwright Inspector which allows you to step through Playwright API calls, see their debug logs and explore [selectors](./selectors.md). +Since Playwright runs in .NET, you can debug it with your debugger of choice in e.g. Visual Studio Code or Visual Studio. Playwright comes with the Playwright Inspector which allows you to step through Playwright API calls, see their debug logs and explore [locators](./locators.md). ```bash tab=bash-bash lang=csharp PWDEBUG=1 dotnet test diff --git a/docs/src/running-tests-js.md b/docs/src/running-tests-js.md index eaedb24440..6e6e7fd886 100644 --- a/docs/src/running-tests-js.md +++ b/docs/src/running-tests-js.md @@ -61,7 +61,7 @@ For a better debugging experience check out the [VS Code Extension](./getting-st ## Debugging Tests -Since Playwright runs in Node.js, you can debug it with your debugger of choice e.g. using `console.log` or inside your IDE or directly in VS Code with the [VS Code Extension](./getting-started-vscode.md). Playwright comes with the [Playwright Inspector](./debug.md#playwright-inspector) which allows you to step through Playwright API calls, see their debug logs and explore [selectors](./selectors.md). +Since Playwright runs in Node.js, you can debug it with your debugger of choice e.g. using `console.log` or inside your IDE or directly in VS Code with the [VS Code Extension](./getting-started-vscode.md). Playwright comes with the [Playwright Inspector](./debug.md#playwright-inspector) which allows you to step through Playwright API calls, see their debug logs and explore [locators](./locators.md). - Debugging all tests: @@ -98,7 +98,7 @@ npx playwright show-report HTML Report > Test Reports view -You can click on each test and explore the tests errors as well as each step of the test. +You can click on each test and explore the tests errors as well as each step of the test. HTML Reporter > Test Reports detailed view diff --git a/docs/src/running-tests-python.md b/docs/src/running-tests-python.md index e250baa94f..f780805434 100644 --- a/docs/src/running-tests-python.md +++ b/docs/src/running-tests-python.md @@ -59,7 +59,7 @@ For more information see [Playwright Pytest usage](./test-runners.md) or the Pyt ## Running Tests -Since Playwright runs in Python, you can debug it with your debugger of choice with e.g. the [Python extension](https://code.visualstudio.com/docs/python/python-tutorial) in Visual Studio Code. Playwright comes with the Playwright Inspector which allows you to step through Playwright API calls, see their debug logs and explore [selectors](./selectors.md). +Since Playwright runs in Python, you can debug it with your debugger of choice with e.g. the [Python extension](https://code.visualstudio.com/docs/python/python-tutorial) in Visual Studio Code. Playwright comes with the Playwright Inspector which allows you to step through Playwright API calls, see their debug logs and explore [locators](./locators.md). ```bash tab=bash-bash lang=python diff --git a/docs/src/testing-library-js.md b/docs/src/testing-library-js.md index 814e565167..93e30a54f2 100644 --- a/docs/src/testing-library-js.md +++ b/docs/src/testing-library-js.md @@ -145,7 +145,6 @@ Learn more about Playwright Test runner: - [Getting Started](./intro) - [Experimental Component Testing](./test-components) -- [Locators](./api/class-locator) -- [Selectors](./selectors) +- [Locators](./locators.md) - [Assertions](./test-assertions) - [Auto-waiting](./actionability) diff --git a/docs/src/why-playwright.md b/docs/src/why-playwright.md index 755f20000f..530f9c9995 100644 --- a/docs/src/why-playwright.md +++ b/docs/src/why-playwright.md @@ -24,13 +24,13 @@ Playwright enables fast, reliable and capable testing and automation across all * **Fast isolation with browser contexts**. Reuse a single browser instance for multiple isolated execution environments with [browser contexts](./browser-contexts.md). -* **Resilient element selectors**. Playwright can rely on user-facing strings, like text content and accessibility labels to [select elements](./selectors.md). These strings are more resilient than selectors tightly-coupled to the DOM structure. +* **Resilient element locators**. Playwright can rely on user-facing strings, like text content and accessibility attributes to [locate elements](./locators.md). These locators are more resilient than selectors tightly-coupled to the DOM structure. ## Powerful automation capabilities * **Multiple domains, pages and frames**. Playwright is an out-of-process automation driver that is not limited by the scope of in-page JavaScript execution and can automate scenarios with [multiple pages](./pages.md). * **Powerful network control**. Playwright introduces context-wide [network interception](./network.md) to stub and mock network requests. -* **Modern web features**. Playwright supports web components through [shadow-piercing selectors](./selectors.md), [geolocation, permissions](./emulation.md), web workers and other modern web APIs. +* **Modern web features**. Playwright supports web components through [shadow-piercing locators](./locators.md), [geolocation, permissions](./emulation.md), web workers and other modern web APIs. * **Capabilities to cover all scenarios**. Support for [file downloads](./downloads.md) and [uploads](./input.md), out-of-process iframes, native [input events](./input.md), and even [dark mode](./emulation.md). diff --git a/docs/src/writing-tests-java.md b/docs/src/writing-tests-java.md index b580bd9b75..17b13d3f53 100644 --- a/docs/src/writing-tests-java.md +++ b/docs/src/writing-tests-java.md @@ -67,7 +67,7 @@ assertThat(getStarted).hasAttribute("href", "/docs/intro"); getStarted.click(); ``` -[Selectors](./selectors.md) are strings that are used to create Locators. Playwright supports many different selectors like [Text](./selectors.md#text-selector), [CSS](./selectors.md#css-selector), [XPath](./selectors.md#xpath-selectors) and many more. Learn more about available selectors and how to pick one in this [in-depth guide](./selectors.md). +Playwright supports many different locators like [role](./locators.md#locate-by-role) [text](./locators.md#get-by-text), [test id](./locators.md#get-by-test-id) and many more. Learn more about available locators and how to pick one in this [in-depth guide](./locators.md). ```java diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.ts index 1eeb1351db..50245746cc 100644 --- a/packages/playwright-core/types/types.d.ts +++ b/packages/playwright-core/types/types.d.ts @@ -291,7 +291,7 @@ export interface Page { * The method finds an element matching the specified selector within the page. If no elements match the selector, the * return value resolves to `null`. To wait for an element on the page, use * [locator.waitFor([options])](https://playwright.dev/docs/api/class-locator#locator-wait-for). - * @param selector A selector to query for. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * @param selector A selector to query for. * @param options */ $(selector: K, options?: { strict: boolean }): Promise | null>; @@ -301,7 +301,7 @@ export interface Page { * The method finds an element matching the specified selector within the page. If no elements match the selector, the * return value resolves to `null`. To wait for an element on the page, use * [locator.waitFor([options])](https://playwright.dev/docs/api/class-locator#locator-wait-for). - * @param selector A selector to query for. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * @param selector A selector to query for. * @param options */ $(selector: string, options?: { strict: boolean }): Promise | null>; @@ -311,7 +311,7 @@ export interface Page { * * The method finds all elements matching the specified selector within the page. If no elements match the selector, * the return value resolves to `[]`. - * @param selector A selector to query for. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * @param selector A selector to query for. */ $$(selector: K): Promise[]>; /** @@ -319,7 +319,7 @@ export interface Page { * * The method finds all elements matching the specified selector within the page. If no elements match the selector, * the return value resolves to `[]`. - * @param selector A selector to query for. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * @param selector A selector to query for. */ $$(selector: string): Promise[]>; @@ -344,7 +344,7 @@ export interface Page { * const preloadHrefTS = await page.$eval('link[rel=preload]', (el: HTMLLinkElement) => el.href); * ``` * - * @param selector A selector to query for. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * @param selector A selector to query for. * @param pageFunction Function to be evaluated in the page context. * @param arg Optional argument to pass to `pageFunction`. * @param options @@ -371,7 +371,7 @@ export interface Page { * const preloadHrefTS = await page.$eval('link[rel=preload]', (el: HTMLLinkElement) => el.href); * ``` * - * @param selector A selector to query for. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * @param selector A selector to query for. * @param pageFunction Function to be evaluated in the page context. * @param arg Optional argument to pass to `pageFunction`. * @param options @@ -398,7 +398,7 @@ export interface Page { * const preloadHrefTS = await page.$eval('link[rel=preload]', (el: HTMLLinkElement) => el.href); * ``` * - * @param selector A selector to query for. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * @param selector A selector to query for. * @param pageFunction Function to be evaluated in the page context. * @param arg Optional argument to pass to `pageFunction`. * @param options @@ -425,7 +425,7 @@ export interface Page { * const preloadHrefTS = await page.$eval('link[rel=preload]', (el: HTMLLinkElement) => el.href); * ``` * - * @param selector A selector to query for. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * @param selector A selector to query for. * @param pageFunction Function to be evaluated in the page context. * @param arg Optional argument to pass to `pageFunction`. * @param options @@ -449,7 +449,7 @@ export interface Page { * const divCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10); * ``` * - * @param selector A selector to query for. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * @param selector A selector to query for. * @param pageFunction Function to be evaluated in the page context. * @param arg Optional argument to pass to `pageFunction`. */ @@ -471,7 +471,7 @@ export interface Page { * const divCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10); * ``` * - * @param selector A selector to query for. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * @param selector A selector to query for. * @param pageFunction Function to be evaluated in the page context. * @param arg Optional argument to pass to `pageFunction`. */ @@ -493,7 +493,7 @@ export interface Page { * const divCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10); * ``` * - * @param selector A selector to query for. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * @param selector A selector to query for. * @param pageFunction Function to be evaluated in the page context. * @param arg Optional argument to pass to `pageFunction`. */ @@ -515,7 +515,7 @@ export interface Page { * const divCounts = await page.$$eval('div', (divs, min) => divs.length >= min, 10); * ``` * - * @param selector A selector to query for. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * @param selector A selector to query for. * @param pageFunction Function to be evaluated in the page context. * @param arg Optional argument to pass to `pageFunction`. */ @@ -624,7 +624,7 @@ export interface Page { * })(); * ``` * - * @param selector A selector to query for. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * @param selector A selector to query for. * @param options */ waitForSelector(selector: K, options?: PageWaitForSelectorOptionsNotHidden): Promise>; @@ -658,7 +658,7 @@ export interface Page { * })(); * ``` * - * @param selector A selector to query for. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * @param selector A selector to query for. * @param options */ waitForSelector(selector: string, options?: PageWaitForSelectorOptionsNotHidden): Promise>; @@ -692,7 +692,7 @@ export interface Page { * })(); * ``` * - * @param selector A selector to query for. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * @param selector A selector to query for. * @param options */ waitForSelector(selector: K, options: PageWaitForSelectorOptions): Promise | null>; @@ -726,7 +726,7 @@ export interface Page { * })(); * ``` * - * @param selector A selector to query for. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * @param selector A selector to query for. * @param options */ waitForSelector(selector: string, options: PageWaitForSelectorOptions): Promise>; @@ -1814,7 +1814,7 @@ export interface Page { * When all steps combined have not finished during the specified `timeout`, this method throws a [TimeoutError]. * Passing zero timeout disables this. * @param selector A selector to search for an element. If there are multiple elements satisfying the selector, the first will be - * used. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * used. * @param options */ check(selector: string, options?: { @@ -1876,7 +1876,7 @@ export interface Page { * When all steps combined have not finished during the specified `timeout`, this method throws a [TimeoutError]. * Passing zero timeout disables this. * @param selector A selector to search for an element. If there are multiple elements satisfying the selector, the first will be - * used. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * used. * @param options */ click(selector: string, options?: { @@ -1997,7 +1997,7 @@ export interface Page { * * **NOTE** `page.dblclick()` dispatches two `click` events and a single `dblclick` event. * @param selector A selector to search for an element. If there are multiple elements satisfying the selector, the first will be - * used. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * used. * @param options */ dblclick(selector: string, options?: { @@ -2094,7 +2094,7 @@ export interface Page { * ``` * * @param selector A selector to search for an element. If there are multiple elements satisfying the selector, the first will be - * used. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * used. * @param type DOM event type: `"click"`, `"dragstart"`, etc. * @param eventInit Optional event-specific initialization properties. * @param options @@ -2131,9 +2131,9 @@ export interface Page { * ``` * * @param source A selector to search for an element to drag. If there are multiple elements satisfying the selector, the first will - * be used. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * be used. * @param target A selector to search for an element to drop onto. If there are multiple elements satisfying the selector, the first - * will be used. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * will be used. * @param options */ dragAndDrop(source: string, target: string, options?: { @@ -2312,7 +2312,7 @@ export interface Page { * To send fine-grained keyboard events, use * [page.type(selector, text[, options])](https://playwright.dev/docs/api/class-page#page-type). * @param selector A selector to search for an element. If there are multiple elements satisfying the selector, the first will be - * used. See [working with selectors](https://playwright.dev/docs/selectors) for more details. + * used. * @param value Value to fill for the ``, `