diff --git a/docs/src/api/class-framelocator.md b/docs/src/api/class-framelocator.md index cdf0ade996..13daae5f94 100644 --- a/docs/src/api/class-framelocator.md +++ b/docs/src/api/class-framelocator.md @@ -9,22 +9,22 @@ await locator.click(); ``` ```java -Locator locator = page.frameLocator("#my-frame").locator("text=Submit"); +Locator locator = page.frameLocator("#my-frame").getByText("Submit"); locator.click(); ``` ```python async -locator = page.frame_locator("#my-frame").locator("text=Submit") +locator = page.frame_locator("#my-frame").get_by_text("Submit") await locator.click() ``` ```python sync -locator = page.frame_locator("my-frame").locator("text=Submit") +locator = page.frame_locator("my-frame").get_by_text("Submit") locator.click() ``` ```csharp -var locator = page.FrameLocator("#my-frame").Locator("text=Submit"); +var locator = page.FrameLocator("#my-frame").GetByText("Submit"); await locator.ClickAsync(); ``` diff --git a/docs/src/api/params.md b/docs/src/api/params.md index 05a1d745dc..fe4732fa5a 100644 --- a/docs/src/api/params.md +++ b/docs/src/api/params.md @@ -1074,7 +1074,7 @@ Text to locate the element for. * since: v1.27 - `exact` <[boolean]> -Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. +Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a regular expression. Note that exact match still trims whitespace. ## locator-get-by-role-role * since: v1.27 @@ -1178,7 +1178,109 @@ Locate element by the test id. By default, the `data-testid` attribute is used a ## template-locator-get-by-text -Allows locating elements that contain given text. +Allows locating elements that contain given text. Consider the following DOM structure: + +```html +
-
-When you have finished interacting with the page, press the **record** button to stop the recording and use the **copy** button to copy the generated code to your editor.
-
-
+
+When you have finished interacting with the page, press the **record** button to stop the recording and use the **copy** button to copy the generated code to your editor.
Use the **clear** button to clear the code to start recording again. Once finished close the Playwright inspector window or stop the terminal command.
-
-
To learn more about generating tests check out or detailed guide on [Codegen](./codegen.md).
-
## What's Next
- [See a trace of your tests](./trace-viewer-intro.md)
diff --git a/docs/src/codegen.md b/docs/src/codegen.md
index 8a63639231..e66a380053 100644
--- a/docs/src/codegen.md
+++ b/docs/src/codegen.md
@@ -5,28 +5,31 @@ title: "Test Generator"
Playwright comes with the ability to generate tests out of the box and is a great way to quickly get started with testing. It will open two windows, a browser window where you interact with the website you wish to test and the Playwright Inspector window where you can record your tests, copy the tests, clear your tests as well as change the language of your tests.
+
## Running Codegen
```bash js
-npx playwright codegen playwright.dev
+npx playwright codegen demo.playwright.dev/todomvc
```
```bash java
-mvn exec:java -e -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args="codegen playwright.dev"
+mvn exec:java -e -Dexec.mainClass=com.microsoft.playwright.CLI -Dexec.args="codegen demo.playwright.dev/todomvc"
```
```bash python
-playwright codegen playwright.dev
+playwright codegen demo.playwright.dev/todomvc
```
```bash csharp
-pwsh bin/Debug/netX/playwright.ps1 codegen playwright.dev
+pwsh bin/Debug/netX/playwright.ps1 codegen demo.playwright.dev/todomvc
```
Run `codegen` and perform actions in the browser. Playwright will generate the code for the user interactions. `Codegen` will attempt to generate resilient text-based selectors.
-
-
+
## Emulate viewport size
@@ -72,8 +75,7 @@ playwright codegen --device="iPhone 11" playwright.dev
pwsh bin/Debug/netX/playwright.ps1 codegen --device="iPhone 11" playwright.dev
```
-
-
+
## Emulate color scheme
diff --git a/docs/src/getting-started-vscode-js.md b/docs/src/getting-started-vscode-js.md
index c416773a55..91cccc3825 100644
--- a/docs/src/getting-started-vscode-js.md
+++ b/docs/src/getting-started-vscode-js.md
@@ -11,7 +11,7 @@ Get started by installing Playwright and generating a test to see it in action.
Install the [VS Code extension from the marketplace](https://marketplace.visualstudio.com/items?itemName=ms-playwright.playwright) or from the extensions tab in VS Code.
-
+
Once installed, open the command panel and type:
@@ -19,39 +19,42 @@ Once installed, open the command panel and type:
Install Playwright
```
-
+
Select **Test: Install Playwright** and Choose the browsers you would like to run your tests on. These can be later configured in the [playwright.config](./test-configuration.md) file. You can also choose if you would like to have a GitHub Actions setup to [run your tests on CI](./ci-intro.md).
-
+
## Running Tests
You can run a single test by clicking the green triangle next to your test block to run your test. Playwright will run through each line of the test and when it finishes you will see a green tick next to your test block as well as the time it took to run the test.
-
+
### Run Tests and Show Browsers
You can also run your tests and show the browsers by selecting the option **Show Browsers** in the testing sidebar. Then when you click the green triangle to run your test the browser will open and you will visually see it run through your test. Leave this selected if you want browsers open for all your tests or uncheck it if you prefer your tests to run in headless mode with no browser open.
-
+
Use the **Close all browsers** button to close all browsers.
-
-
### View and Run All Tests
View all tests in the testing sidebar and extend the tests by clicking on each test. Tests that have not been run will not have the green check next to them. Run all tests by clicking on the white triangle as you hover over the tests in the testing sidebar.
-
+
### Run Tests on Specific Browsers
-The VS Code test runner runs your tests on the default browser of Chrome. To run on other/multiple browsers click the play button's dropdown and choose the option of "Select Default Profile" and select the browsers you wish to run your tests on.
+The VS Code test runner runs your tests on the default browser of Chrome. To run on other/multiple browsers click the play button's dropdown and choose another profile or modify the default profile by clicking **Select Default Profile** and select the browsers you wish to run your tests on.
-
+
+
+
+Choose various or all profiles to run tests on multiple profiles. These profiles are read from the [playwright.config](./test-configuration.md) file. To add more profiles such as a mobile profile, first add it to your config file and it will then be available here.
+
+
## Debugging Tests
@@ -61,13 +64,13 @@ With the VS Code extension you can debug your tests right in VS Code see error m
If your test fails VS Code will show you error messages right in the editor showing what was expected, what was received as well as a complete call log.
-
+
### Run in Debug Mode
To set a breakpoint click next to the line number where you want the breakpoint to be until a red dot appears. Run the tests in debug mode by right clicking on the line next to the test you want to run. A browser window will open and the test will run and pause at where the breakpoint is set.
-
+
### Live Debugging
@@ -75,37 +78,42 @@ To set a breakpoint click next to the line number where you want the breakpoint
You can modify your test right in VS Code while debugging and Playwright will highlight the selector in the browser. This is a great way of seeing if the selector exits or if there is more than one result. You can step through the tests, pause the test and rerun the tests from the menu in VS Code.
-
+
+### Debug in different Browsers
+Debug your tests on specific browsers by selecting a profile from the dropdown. Set the default profile or select more than one profile to debug various profiles. Playwright will launch the first profile and once finished debugging it will then launch the next one.
+
+
+
+To learn more about debugging, see [Debugging in Visual Studio Code](https://code.visualstudio.com/docs/editor/debugging).
## Generating Tests
CodeGen will auto generate your tests for you as you perform actions in the browser and is a great way to quickly get started. The viewport for the browser window is set to a specific width and height. See the [configuration guide](./test-configuration.md) to change the viewport or emulate different environments.
+
### Record a New Test
To record a test click on the **Record new** button from the Testing sidebar. This will create a `test-1.spec.ts` file as well as open up a browser window. In the browser go to the URL you wish to test and start clicking around. Playwright will record your actions and generate a test for you. Once you are done recording click the **cancel** button or close the browser window. You can then inspect your `test-1.spec.ts` file and see your generated test.
-
+
-### Record a Test Starting From Another Test
+### Record From Here
-Use the **Record from here** button to record a test from a specific line in your test file. This will open up a browser window and record the test from the line you selected. A new test file will now be created with the name `test-2.spec.ts` and will include the test code up to the selected line of the test file where you ran the **Record from here** button. You can then continue to generate the new test by clicking around in the browser window.
+Record a new test snippet. This creates a new empty test file but the recording starts from the current browser state from the previous test instead of starting a new browser. This snippet can then be pasted into a previous test file so it can be properly run. Note in the example below the test starts from the last state of a previous test and therefore has no `page.goto()` action.
-
-### Selector Highlighting
-
-As you interact with the page Codegen will generate the test for you in the newly created file in VS Code. When you hover over an element Playwright will highlight the element and show the [selector](./selectors.md) underneath it.
-
-
+
### Picking a Selector
Pick a selector and copy it into your test file by clicking the **Pick selector** button form the testing sidebar. Then in the browser click the selector you require and it will now show up in the **Pick selector** box in VS Code. Press 'enter' on your keyboard to copy the selector into the clipboard and then paste anywhere in your code. Or press 'escape' if you want to cancel.
-
+
diff --git a/docs/src/handles.md b/docs/src/handles.md
index e2c1c75917..5b42e33b5c 100644
--- a/docs/src/handles.md
+++ b/docs/src/handles.md
@@ -253,3 +253,79 @@ unless page navigates or the handle is manually disposed via the [`method: JSHan
- [`method: Page.evaluateHandle`]
- [`method: Page.querySelector`]
- [`method: Page.querySelectorAll`]
+
+
+## Locator vs ElementHandle
+
+:::caution
+We only recommend using [ElementHandle] in the rare cases when you need to perform extensive DOM traversal
+on a static page. For all user actions and assertions use locator instead.
+:::
+
+The difference between the [Locator] and [ElementHandle] is that the latter points to a particular element, while Locator captures the logic of how to retrieve that element.
+
+In the example below, handle points to a particular DOM element on page. If that element changes text or is used by React to render an entirely different component, handle is still pointing to that very stale DOM element. This can lead to unexpected behaviors.
+
+```js
+const handle = await page.$('text=Submit');
+// ...
+await handle.hover();
+await handle.click();
+```
+
+```java
+ElementHandle handle = page.querySelector("text=Submit");
+handle.hover();
+handle.click();
+```
+
+```python async
+handle = await page.query_selector("text=Submit")
+await handle.hover()
+await handle.click()
+```
+
+```python sync
+handle = page.query_selector("text=Submit")
+handle.hover()
+handle.click()
+```
+
+```csharp
+var handle = await page.QuerySelectorAsync("text=Submit");
+await handle.HoverAsync();
+await handle.ClickAsync();
+```
+
+With the locator, every time the locator is used, up-to-date DOM element is located in the page using the selector. So in the snippet below, underlying DOM element is going to be located twice.
+
+```js
+const locator = page.getByText('Submit');
+// ...
+await locator.hover();
+await locator.click();
+```
+
+```java
+Locator locator = page.getByText("Submit");
+locator.hover();
+locator.click();
+```
+
+```python async
+locator = page.get_by_text("Submit")
+await locator.hover()
+await locator.click()
+```
+
+```python sync
+locator = page.get_by_text("Submit")
+locator.hover()
+locator.click()
+```
+
+```csharp
+var locator = page.GetByText("Submit");
+await locator.HoverAsync();
+await locator.ClickAsync();
+```
diff --git a/docs/src/locators.md b/docs/src/locators.md
index 5eca419fb7..c553b50573 100644
--- a/docs/src/locators.md
+++ b/docs/src/locators.md
@@ -4,31 +4,68 @@ title: "Locators"
---
[Locator]s are the central piece of Playwright's auto-waiting and retry-ability. In a nutshell, locators represent
-a way to find element(s) on the page at any moment. Locator can be created with the [`method: Page.locator`] method.
+a way to find element(s) on the page at any moment.
+
+### Quick Guide
+
+These are the recommended built in locators.
+
+- [`method: Page.getByRole`] to locate by explicit and implicit accessibility attributes.
+- [`method: Page.getByText`] to locate by text content.
+- [`method: Page.getByLabel`] to locate a form control by associated label's text.
+- [`method: Page.getByPlaceholder`] to locate an input by placeholder.
+- [`method: Page.getByAltText`] to locate an element, usually image, by its text alternative.
+- [`method: Page.getByTitle`] to locate an element by its title.
+- [`method: Page.getByTestId`] to locate an element based on its `data-testid` attribute (other attribute can be configured).
```js
-const locator = page.getByText('Submit');
-await locator.click();
+await page.getByLabel('User Name').fill('John');
+
+await page.getByLabel('Password').fill('secret-password');
+
+await page.getByRole('button', { name: 'Sign in' }).click();
+
+await expect(page.getByText('Welcome, John!')).toBeVisible();
```
```java
-Locator locator = page.getByText("Submit");
-locator.click();
+page.getByLabel("User Name").fill("John");
+
+page.getByLabel("Password").fill("secret-password");
+
+page.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Sign in")).click();
+
+assertThat(page.getByText("Welcome, John!")).isVisible();
```
```python async
-locator = page.get_by_text("Submit")
-await locator.click()
+await page.get_by_label("User Name").fill("John")
+
+await page.get_by_label("Password").fill("secret-password")
+
+await page.get_by_role("button", name="Sign in").click()
+
+await expect(page.get_by_text("Welcome, John!")).to_be_visible()
```
```python sync
-locator = page.get_by_text("Submit")
-locator.click()
+page.get_by_label("User Name").fill("John")
+
+page.get_by_label("Password").fill("secret-password")
+
+page.get_by_role("button", name="Sign in").click()
+
+expect(page.get_by_text("Welcome, John!")).to_be_visible()
```
```csharp
-var locator = page.GetByText("Submit");
-await locator.ClickAsync();
+await page.GetByLabel("User Name").FillAsync("John");
+
+await page.GetByLabel("Password").FillAsync("secret-password");
+
+await page.GetByRole("button", new() { Name = "Sign in" }).ClickAsync();
+
+await Expect(page.GetByText("Welcome, John!")).ToBeVisibleAsync();
```
Every time locator is used for some action, up-to-date DOM element is located in the page. So in the snippet
@@ -71,75 +108,57 @@ await locator.ClickAsync();
Locators are strict. This means that all operations on locators that imply
some target DOM element will throw an exception if more than one element matches
-given selector.
+given selector. For example, the following call throws if there are several buttons in the DOM:
```js
-// Throws if there are several buttons in DOM:
await page.getByRole('button').click();
+```
-// Works because we explicitly tell locator to pick the first element:
-await page.getByRole('button').first().click(); // ⚠️ using first disables strictness
+```python async
+await page.get_by_role("button").click()
+```
-// Works because count knows what to do with multiple matches:
+```python sync
+page.get_by_role("button").click()
+```
+
+```java
+page.getByRole("button").click();
+```
+
+```csharp
+await page.GetByRole("button").ClickAsync();
+```
+
+On the other hand, Playwright understands when you perform a multiple-element operation,
+so the following call works perfectly fine when locator resolves to multiple elements.
+
+```js
await page.getByRole('button').count();
```
```python async
-# Throws if there are several buttons in DOM:
-await page.get_by_role("button").click()
-
-# Works because we explicitly tell locator to pick the first element:
-await page.get_by_role("button").first.click() # ⚠️ using first disables strictness
-
-# Works because count knows what to do with multiple matches:
await page.get_by_role("button").count()
```
```python sync
-# Throws if there are several buttons in DOM:
-page.get_by_role("button").click()
-
-# Works because we explicitly tell locator to pick the first element:
-page.get_by_role("button").first.click() # ⚠️ using first disables strictness
-
-# Works because count knows what to do with multiple matches:
page.get_by_role("button").count()
```
```java
-// Throws if there are several buttons in DOM:
-page.getByRole("button").click();
-
-// Works because we explicitly tell locator to pick the first element:
-page.getByRole("button").first().click(); // ⚠️ using first disables strictness
-
-// Works because count knows what to do with multiple matches:
page.getByRole("button").count();
```
```csharp
-// Throws if there are several buttons in DOM:
-await page.GetByRole("button").ClickAsync();
-
-// Works because we explicitly tell locator to pick the first element:
-await page.GetByRole("button").First.ClickAsync(); // ⚠️ using First disables strictness
-
-// Works because Count knows what to do with multiple matches:
await page.GetByRole("button").CountAsync();
```
-:::caution
-Using [`method: Locator.first`], [`method: Locator.last`], and [`method: Locator.nth`] is discouraged since it disables the concept of strictness, and as your page changes, Playwright may click on an element you did not intend. It's better to make your locator more specific.
-:::
+You can explicitly opt-out from strictness check by telling Playwright which element to use when multiple element match, through [`method: Locator.first`], [`method: Locator.last`], and [`method: Locator.nth`]. These methods are **not recommended** because when your page changes, Playwright may click on an element you did not intend. Instead, follow best practices below to create a locator that uniquely identifies the target element.
## Locating elements
-Use [`method: Page.locator`] method to create a locator. This method takes a selector that describes how to find an element in the page. The choice of selectors determines the resiliency of the test when the underlying web page changes. To reduce the maintenance burden, we recommend prioritizing user-facing attributes and explicit contracts.
-
-### Locate by text content using `text=`
-
-The easiest way to find an element is to look for the text it contains.
+Playwright comes with multiple built-in ways to create a locator. To make tests resilient, we recommend prioritizing user-facing attributes and explicit contracts, and provide dedicated methods for them, such as [`method: Page.getByText`]. It is often convenient to use the [code generator](./codegen.md) to generate a locator, and then edit it as you'd like.
```js
await page.getByText('Log in').click();
@@ -157,29 +176,38 @@ page.get_by_text("Log in").click()
await page.GetByText("Log in").ClickAsync();
```
-You can also [filter by text](#filter-by-text) when locating in some other way, for example find a particular item in the list.
+If you absolutely must use CSS or XPath locators, you can use [`method: Page.locator`] to create a locator that takes a [selector](./selectors.md) describing how to find an element in the page.
+
+Note that all methods that create a locator, such as [`method: Page.getByLabel`], are also available on the [Locator] and [FrameLocator] classes, so you can chain them and iteratively narrow down your locator.
```js
-await page.locator('data-test-id=product-item', { hasText: 'Playwright Book' }).click();
+const locator = page.frameLocator('#my-frame').getByText('Submit');
+await locator.click();
```
+
```java
-page.locator("data-test-id=product-item", new Page.LocatorOptions().setHasText("Playwright Book")).click();
+Locator locator = page.frameLocator("#my-frame").getByText("Submit");
+locator.click();
```
+
```python async
-await page.locator("data-test-id=product-item", has_text="Playwright Book").click()
+locator = page.frame_locator("#my-frame").get_by_text("Submit")
+await locator.click()
```
+
```python sync
-page.locator("data-test-id=product-item", has_text="Playwright Book").click()
+locator = page.frame_locator("my-frame").get_by_text("Submit")
+locator.click()
```
+
```csharp
-await page.Locator("data-test-id=product-item", new() { HasText = "Playwright Book" }).ClickAsync();
+var locator = page.FrameLocator("#my-frame").GetByText("Submit");
+await locator.ClickAsync();
```
-[Learn more about the `text` selector](./selectors.md#text-selector).
+### Locate based on accessible attributes
-### Locate based on accessible attributes using `role=`
-
-The `role` selector reflects how users and assistive technology percieve the page, for example whether some element is a button or a checkbox. When locating by role, you should usually pass the accessible name as well, so that locator pinpoints the exact element.
+The [`method: Page.getByRole`] locator reflects how users and assistive technology perceive the page, for example whether some element is a button or a checkbox. When locating by role, you should usually pass the accessible name as well, so that locator pinpoints the exact element.
```js
await page.getByRole('button', { name: /submit/i }).click();
@@ -188,113 +216,255 @@ await page.getByRole('checkbox', { checked: true, name: "Check me" }).check();
```
```python async
-await page.get_by_role("button", name=re.compile("(?i)submit")).click()
+await page.get_by_role("button", name=re.compile("submit", re.IGNORECASE)).click()
-await page.get_by_role("checkbox", checked=True, name="Check me"]).check()
+await page.get_by_role("checkbox", checked=True, name="Check me").check()
```
```python sync
-page.get_by_role("button", name=re.compile("(?i)submit")).click()
+page.get_by_role("button", name=re.compile("submit", re.IGNORECASE)).click()
-page.get_by_role("checkbox", checked=True, name="Check me"]).check()
+page.get_by_role("checkbox", checked=True, name="Check me").check()
```
```java
-page.getByRole("button", new Page.GetByRoleOptions().setName(Pattern.compile("(?i)submit"))).click();
+page.getByRole("button", new Page.GetByRoleOptions().setName(Pattern.compile("submit", Pattern.CASE_INSENSITIVE))).click();
page.getByRole("checkbox", new Page.GetByRoleOptions().setChecked(true).setName("Check me"))).check();
```
```csharp
-await page.GetByRole("button", new() { Name = new Regex("(?i)submit") }).ClickAsync();
+await page.GetByRole("button", new() { Name = new Regex("submit", RegexOptions.IgnoreCase) }).ClickAsync();
await page.GetByRole("checkbox", new() { Checked = true, Name = "Check me" }).CheckAsync();
```
-[Learn more about the `role` selector](./selectors.md#role-selector).
+Role locators 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).
-### Define explicit contract and use `data-test-id=`
-
-User-facing attributes like text or accessible name can change frequently. In this case it is convenient to define explicit test ids, for example with a `data-test-id` attribute. Playwright has dedicated support for `id`, `data-test-id`, `data-test` and `data-testid` attributes.
-
-```html
-
-```
-
-```js
-await page.locator('data-test-id=directions').click();
-```
-
-```java
-page.locator("data-test-id=directions").click();
-```
-
-```python async
-await page.locator('data-test-id=directions').click()
-```
-
-```python sync
-page.locator('data-test-id=directions').click()
-```
-
-```csharp
-await page.Locator("data-test-id=directions").ClickAsync();
-```
+Note that role locators **do not replace** accessibility audits and conformance tests, but rather give early feedback about the ARIA guidelines.
### Locate by label text
-Most form controls usually have dedicated labels that could be conveniently used to interact with the form. Input actions in Playwright automatically distinguish between labels and controls, so you can just locate the label to perform an action on the associated control.
+Most form controls usually have dedicated labels that could be conveniently used to interact with the form. In this case, you can locate the control by its associated label using [`method: Page.getByLabel`].
For example, consider the following DOM structure.
```html
-
+
```
-You can target the label with something like `text=Password` and perform the following actions on the password input:
-- `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.
-
-For example, to fill the input by targeting the label:
+You can fill the input after locating it by the label text:
```js
-await page.getByText('Password').fill('secret');
+await page.getByLabel('Password').fill('secret');
```
```java
-page.getByText("Password").fill("secret");
+page.getByLabel("Password").fill("secret");
```
```python async
-await page.get_by_text('Password').fill('secret')
+await page.get_by_label("Password").fill("secret")
```
```python sync
-page.get_by_text('Password').fill('secret')
+page.get_by_label("Password").fill("secret")
```
```csharp
-await page.GetByText("Password").FillAsync("secret");
+await page.GetByLabel("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.
+### Locate by placeholder text
+
+Inputs may have a placeholder attribute to hint to the user what value should be entered. You can locate such an input using [`method: Page.getByPlaceholder`].
+
+For example, consider the following DOM structure.
+
+```html
+
+```
+
+You can fill the input after locating it by the placeholder text:
+
+```js
+await page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");
+```
+
+```java
+page.getByPlaceholder("name@example.com").fill("playwright@microsoft.com");
+```
+
+```python async
+await page.get_by_placeholder("name@example.com").fill("playwright@microsoft.com")
+```
+
+```python sync
+page.get_by_placeholder("name@example.com").fill("playwright@microsoft.com")
+```
+
+```csharp
+await page.GetByPlacheolder("name@example.com").FillAsync("playwright@microsoft.com");
+```
+
+### Locate by text
+
+The easiest way to find an element is to look for the text it contains. You can match by a substring, exact string, or a regular expression when using [`method: Page.getByText`].
+
+```js
+await page.getByText('Log in').click();
+await page.getByText('Log in', { exact: true }).click();
+await page.getByText(/log in$/i).click();
+```
+```java
+page.getByText("Log in").click();
+page.getByText("Log in", new Page.GetByTextOptions().setExact(true)).click();
+page.getByText(Pattern.compile("log in$", Pattern.CASE_INSENSITIVE)).click();
+```
+```python async
+await page.get_by_text("Log in").click()
+await page.get_by_text("Log in", exact=True).click()
+await page.get_by_text(re.compile("Log in", re.IGNORECASE)).click()
+```
+```python sync
+page.get_by_text("Log in").click()
+page.get_by_text("Log in", exact=True).click()
+page.get_by_text(re.compile("Log in", re.IGNORECASE)).click()
+```
+```csharp
+await page.GetByText("Log in").ClickAsync();
+await page.GetByText("Log in", new() { Exact: true }).ClickAsync();
+await page.GetByText(new Regex("Log in", RegexOptions.IgnoreCase)).ClickAsync();
+```
+
+You can also [filter by text](#filter-by-text) when locating in some other way, for example find a particular item in the list.
+
+```js
+await page.getByTestId('product-item').filter({ hasText: 'Playwright Book' }).click();
+```
+```java
+page.getByTestId("product-item").filter(new Locator.FilterOptions().setHasText("Playwright Book")).click();
+```
+```python async
+await page.get_by_test_id("product-item").filter(has_text="Playwright Book").click()
+```
+```python sync
+page.get_by_test_id("product-item").filter(has_text="Playwright Book").click()
+```
+```csharp
+await page.GetByTestId("product-item").Filter(new() { HasText = "Playwright Book" }).ClickAsync();
+```
+
+:::note
+Matching by text always normalizes whitespace, even with exact match. For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace.
+:::
+
+### Locate by alt text
+
+All images should have an `alt` attribute that describes the image. You can locate an image based on the text alternative using [`method: Page.getByAltText`].
+
+
+For example, consider the following DOM structure.
+
+```html
+
+```
+
+You can click on the image after locating it by the text alternative:
+
+```js
+await page.getByAltText('playwright logo').click();
+```
+
+```java
+page.getByAltText("playwright logo").click();
+```
+
+```python async
+await page.get_by_alt_text("playwright logo").click()
+```
+
+```python sync
+page.get_by_alt_text("playwright logo").click()
+```
+
+```csharp
+await page.GetByAltText("playwright logo").ClickAsync();
+```
+### Locate by title
+
+Locate an element with a matching title attribute using [`method: Page.getByTitle`].
+
+For example, consider the following DOM structure.
+
+```html
+25 issues
+```
+
+You can check the issues count after locating it by the title text:
+
+```js
+await expect(page.getByTitle('Issues count')).toHaveText('25 issues');
+```
+
+```java
+assertThat(page.getByTitle("Issues count")).hasText("25 issues");
+```
+
+```python async
+await expect(page.get_by_title("Issues count")).to_have_text("25 issues")
+```
+
+```python sync
+expect(page.get_by_title("Issues count")).to_have_text("25 issues")
+```
+
+```csharp
+await Expect(page.GetByTitle("Issues count")).toHaveText("25 issues");
+```
+
+### Define explicit contract and use a data-testid attribute
+
+User-facing attributes like text or accessible name can change over time. In this case it is convenient to define explicit test ids and query them with [`method: Page.getByTestId`].
+
+```html
+
+```
+
+```js
+await page.getByTestId('directions').click();
+```
+
+```java
+page.getByTestId("directions").click();
+```
+
+```python async
+await page.get_by_test_id("directions").click()
+```
+
+```python sync
+page.get_by_test_id("directions").click()
+```
+
+```csharp
+await page.GetByTestId("directions").ClickAsync();
+```
+
+By default, [`method: Page.getByTestId`] will locate elements based on the `data-testid` attribute, but you can configure it in your test config or calling [`method: Selectors.setTestIdAttribute`].
### Locate in a subtree
-You can chain [`method: Page.locator`] and [`method: Locator.locator`] calls to narrow down the search to a particular part of the page.
+You can chain methods that create a locator, like [`method: Page.getByText`] or [`method: Locator.getByRole`], to narrow down the search to a particular part of the page.
For example, consider the following DOM structure:
```html
-
+
Check out our [debugging guide](./debug.md) to learn more about the [Playwright Inspector](./debug.md#playwright-inspector) as well as debugging with [Browser Developer tools](./debug.md#browser-developer-tools).
diff --git a/docs/src/selectors.md b/docs/src/selectors.md
index 6615f6e5e7..3a5a96e81e 100644
--- a/docs/src/selectors.md
+++ b/docs/src/selectors.md
@@ -236,7 +236,7 @@ await page.Locator("text=Log in").ClickAsync();
Text selector has a few variations:
-- `text=Log in` - default matching is case-insensitive and searches for a substring. For example, `text=Log` matches ``.
+- `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();
@@ -254,7 +254,7 @@ Text selector has a few variations:
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. For example, `text="Log"` does not match `` because `