Get List of Elements in Playwright Java

Profile picture for user arilio666

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

  page.navigate("https://www.programsbuzz.com/search/node?keys=playwright+java");

        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.

       page.navigate("https://www.programsbuzz.com/search/node?keys=playwright+java");

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

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

        System.out.println(textContent); 

3. Display a list of texts

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

        page.navigate("https://www.programsbuzz.com/search/node?keys=playwright+java");

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

        List<String> allTextContents = listEle.allTextContents();
        System.out.println(allTextContents);