Playwright Getting List of Elements

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

We will be considering the following page for various examples that are going to be shown.


List Element Page

1. Get the count of elements present

  • The list has four items. Using the count assertion, we can verify that.
const {test, expect} = require('@playwright/test');

test.use({
 ignoreHTTPSErrors: true
});

test('test', async ({ page }) => {

 await page.goto('http://autopract.com/selenium/parents.html');
 await expect(page.locator('.menu li')).toHaveCount(4);




});

2. Assert text present in the list

  • The list of elements contains names that we can assert using the playwright.
const {test, expect} = require('@playwright/test');

test.use({
 ignoreHTTPSErrors: true
});

test('test', async ({ page }) => {

 await page.goto('http://autopract.com/selenium/parents.html');
 await expect(page.locator('.menu li')).toHaveText(['Item 1','Item 2','Item 3','Item 4']);




});

3. Nth content filter

  • In the playwright's list of elements, we can fetch the nth place of the text from the various texts.
const {test, expect} = require('@playwright/test');

test.use({
 ignoreHTTPSErrors: true
});

test('test', async ({ page }) => {

 await page.goto('http://autopract.com/selenium/parents.html');
 const textContent = await page.locator('.menu li').nth(2).textContent();
 console.log(textContent);




});

4. Using a filter

  • We can perform a click operation over the specified text using the filter.
const {test, expect} = require('@playwright/test');

test.use({
 ignoreHTTPSErrors: true
});

test('test', async ({ page }) => {

 await page.goto('http://autopract.com/selenium/parents.html');
 await page.locator('.menu li').filter({ hasText: 'Item 2' }).dblclick;




});

5. Display a list of texts

  • Using allTextContent, we can fetch the list of elements present.
const {test, expect} = require('@playwright/test');

test.use({
 ignoreHTTPSErrors: true
});

test('test', async ({ page }) => {

 await page.goto('http://autopract.com/selenium/parents.html');
 const allText = await page.locator('.menu li').allTextContents();
 console.log(allText)



});

Test Report
 

Thu, 11/24/2022 - 08:27
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.

Comments