Playwright Get Text Content from List of Elements

Playwright Get Text Content from List of Elements

  • In this article, we will get all text contents from a list of elements.
  • We will be doing this on our programsbuzz site.
  • We will be clicking on the search bar of the site.
  • Type in cypress and fetch all the search result titles of cypress as text.

Before we dive into this concept, we will see what type of application is running on this site.

  • As soon as we type in cypress and hit search, we can see that calls are made on the site.
  • This is the progress of fetching the items and displaying them for us from one end. We call it a service-oriented application.

Let us see what happens when we try to get all the text content.

const {test, expect} = require('@playwright/test');
test('TEXTS', async ({page})=> 
{

await page.goto("https://www.programsbuzz.com/");

await page.locator('.gv-icon-52').click()
await page.locator('#edit-keys').type('cypress')
await page.locator('#edit-submit').click()
const titles = await page.locator('ol h3').allTextContents()
console.log(titles)

});

  • We got ourselves some empty array even when we took the searched up titles is displayed.
  • 'ol h3' fetches all the page title currently in.

So what could have gone wrong?

For service-oriented applications we can use,

await page.waitForLoadState('networkidle')
  • This means we are asking for the page to wait for load state till the network is idle, i.e., till all the network calls are made, and the results are displayed.
const {test, expect} = require('@playwright/test');
test('TEXTS', async ({page})=> 
{

await page.goto("https://www.programsbuzz.com/");

await page.locator('.gv-icon-52').click()
await page.locator('#edit-keys').type('cypress')
await page.locator('#edit-submit').click()
await page.waitForLoadState('networkidle')
const titles = await page.locator('ol h3').allTextContents()
console.log(titles)

});

  • There we go. All the text contents are fetched after waiting for the network to idle using the allTextContents() method.
Standard (Image)