Location>code7788 >text

A First Look at the "Just Asked" Series - Java+Playwright Automated Testing - 7 - Basic Element Positioning Methods - Next (Detailed Tutorial)

Popularity:165 ℃/2024-12-19 19:19:25

1. Introduction

The previous article explained the theoretical basics of some of the more common basic positioning methods that we use in our daily work to position elements using Playwright, and under what circumstances it is recommended to use them. Today, this article explains and shares the remaining part of the basic positioning methods.

2. Filter positioning

Take for example the following DOM structure where we want to click on the Buy button for the second product card. We have several options to filter the locator to get the correct one.

2.1 Filtering by text

The locator can be filtered by text using the () method. It will search for a specific string somewhere within the element, possibly in descendant elements, case-insensitively. You can also pass regular expressions.

1. Use of text

()
    .filter(new ().setHasText("Product 2"))
    .getByRole(,
               new ().setName("Add to cart"))
    .click();

2. Use regular expressions

()
    .filter(new ()
        .setHasText(("Product 2")))
    .getByRole(,
               new ().setName("Add to cart"))
    .click();

2.2 Filtering by absence of text

Filtering by absence of text:

// 5 in-stock items
assertThat(()
    .filter(new ().setHasNotText("Out of stock")))
    .hasCount(5);

2.3 Sub/offspring filtering

Locators support an option to select only elements that have or do not have descendants that match another locator. Therefore, you can filter by any other locator such as (), (), (), etc.

()
    .filter(new ()
        .setHas((, new ()
        .setName("Product 2"))))
    .getByRole(,
               new ().setName("Add to cart"))
    .click()

We can also assert the product card to make sure there is only one:

assertThat(page
    .getByRole()
    .filter(new ()
        .setHas((,
                               new ().setName("Product 2"))))
    .hasCount(1);

filter positionerThe query must be performed relative to the original locator and start from the original locator match, not from the document root. As a result, the following will not work because the filter locator starts matching from a list element that is outside the list item matched by the original locator:<ul><li>

// ✖ WRONG
assertThat(page
    .getByRole()
    .filter(new ()
        .setHas(()
                    .GetByRole(,
                               new ().setName("Product 2"))))
    .hasCount(1);

2.4 Filtering by no children/descendants

We can also use the internalThere are no matching elements to filter.

assertThat(page
    .getByRole()
    .filter(new ().setHasNot(("Product 2")))
    .hasCount(1);

Blackboard !!!! Note that the internal locator is matched from the external locator, not from the document root.

3. Positioner operator

3.1 Positioner internal matching

You can link to methods for creating locators, such as () or (), to narrow your search to specific parts of the page.

In this example, we first create a locator named product by locating its role listitem. Then, we filter by text. We can use the product locator again to get the role of the button and click on it, and then use an assertion to make sure there is only one product with the text "product 2".

Locator product = page
    .getByRole()
    .filter(new ().setHasText("Product 2"));

product
    .getByRole(,
               new ().setName("Add to cart"))
    .click();

You can also link two locators together, for example, by looking for the Save button in a specific dialog box:

Locator saveButton = (,
                                    new ().setName("Save"));
// ...
Locator dialog = ("settings-dialog");
(saveButton).click();

3.2 Matching two positioners simultaneously

Method () narrows the scope of an existing locator by matching other locators. For example, you can combine () and () to match by role and title.

Locator button = ().and(("Subscribe"));

3.3 Match one of the two alternative positioners

If you want to locate one of two or more elements, but don't know which one it will be, use () to create a locator that matches all the alternatives.

For example, consider a situation where you want to click the New E-mail button, but sometimes the Security Settings dialog box appears. In this case, you can wait for the New E-mail button or dialog box and then take the appropriate action.

Knock on wood!!! Attention:

If both the New Email button and the security dialog box appear on the screen, the "or" locator will match them, potentially triggering a Strict Mode Violation error. In this case, you can use () to match only one of them.

Locator newEmail = (, new ().setName("New"));
Locator dialog = ("Confirm security settings");
assertThat((dialog).first()).isVisible();
if (())
  (, new ().setName("Dismiss")).click();
();

3.4 Match only visible elements

Knock on wood!!! Attention:

Often, it is more reliable to find a way to uniquely identify elements rather than checking for visibility.

Consider a page with two buttons, the first invisible and the second visible.

<button style='display: none'>Invisible</button>
<button>Visible</button>

This will find two buttons and throw a strictness violation error:

("button").click();

This will only find the second button as it is visible, then click on it.

("button").locator("visible=true").click();

4. List

4.1 Counting items in a list

A locator can be asserted to count items in a list. For example, the following DOM structure

Use the count assertion to ensure that the list contains 3 items.

assertThat(().hasCount(3);

4.2 Asserting all text in a list

The locator can be asserted to find all text in the list. For example, the following DOM structure

Use assertThat(locator).hasText() to ensure that the list contains the text "apple", "banana" and "orange ".

assertThat(page
    .getByRole())
    .hasText(new String[] { "apple", "banana", "orange" });

4.3 Positioning specific projects

There are many ways to locate specific items in a list.

4.3.1 Positioning through text

Use the () method to find an element in a list by its text content and then click on it. For example, the following DOM structure

Locate the item by its text content and click on it.

("orange").click();
4.3.2 Positioning by text filtering

Use () to find a specific item in a list. For example, the following DOM structure

Press the "listitem" role to find an item, then press the "orange" text to filter and click on it.

()
    .filter(new ().setHasText("orange"))
    .click();
4.3.3 Localization through test ids

Use the () method to find elements in the list. If you don't already have a test ID, you may need to modify the html and add a test ID.

Find an item with the test ID "orange" and click on it.

("orange").click();
4.3.4 Positioning through the nth term

If you have a list of identical elements and the only way to distinguish between them is by order, you can use (), () or () to select specific elements from the list.

Locator banana = ().nth(1);

However, please use this method with caution. Often, the page may change and the locator will point to a completely different element than you expected. Instead, try to come up with a unique locator that will pass strict criteria.

4.4 Link Filter

When you have elements with various similarities, you can use the () method to select the correct element. You can also link multiple filters to narrow the selection.

To take a screenshot of the line with "Mary" and "Say goodbye", do the following:

Locator rowLocator = ();

rowLocator
    .filter(new ().setHasText("Mary"))
    .filter(new ()
        .setHas((
            ,
            new ().setName("Say goodbye"))))
    .screenshot(new ().setPath(""));

You should now have a "" file in the root directory of your project.

4.5 Rare examples

4.5.1 Performing certain operations on each element of a list

iterative element (math.)

for (Locator row : ().all())
  (());

Iterate using a regular for loop:

Locator rows = ();
int count = ();
for (int i = 0; i < count; ++i)
  ((i).textContent());
4.5.2 On-page evaluation

The code in locator.evaluate_all() runs in the page where you can call any DOM API.

Locator rows = ();
Object texts = (
    "list => (element => )");

5. Summary

Locators are very strict. This means that all operations performed on locators that imply some target DOM element will raise an exception if multiple elements match. For example, if there are multiple buttons in the DOM, the following call will be raised:

Raises an error if there is more than one button

().click();

On the other hand, Playwright knows when to perform multi-element operations, so the following calls work fine when the locator resolves to more than one element.

Applies to multiple elements

().count();

You can explicitly opt out of strictness checking by telling Playwright which element to use when multiple elements match via , , and (). These methods are not recommended, as Playwright may click on elements you don't want when your page changes. Instead, follow the best practices above to create locators that uniquely identify the target element.

5.1 Other positioners

For less common locators, check out the official website of theOther positionersGuide. Due to time constraints, Macro will not expand on it and explain it here. Well time is running out, about the elements of the basic positioning way to share here today!!!! Only for your study reference, thank you for your patience to read.