Get List of Elements in Playwright Java

In playwright java, we can get the count of lists of elements on a page or even get assertions out of the list of elements on the page.

This page has some titles, which are a total of 10. We will get the list of the tags and operate them.

1. Get the count of elements present


        Locator listEle = page.locator("//h3[@class='search-result__title']");

        int count = listEle.count();

        Assert.assertEquals(count, 10);  

Using the TesNG's assert privilege, we can get the count and assert the list of elements present.

2. Nth content filter

Using the nth method, we can isolate the text content of the list of elements and print it.


        Locator listEle = page.locator("//h3[@class='search-result__title']");

        String textContent = listEle.nth(1).textContent();


3. Display a list of texts

We can also use the allTextContents method and print all the texts from the list of elements.


        Locator listEle = page.locator("//h3[@class='search-result__title']");

        List<String> allTextContents = listEle.allTextContents();
Fri, 03/17/2023 - 10:35
Ashwin possesses over five years of experience in the Quality Assurance industry and is currently serving as a Technical Lead at iVagus. His expertise encompasses a broad range of technologies, including Cypress, Rest Assured, Selenium, Cucumber, JavaScript and TypeScript.