Get List of Elements in Playwright Python

Profile picture for user arilio666

In playwright python, 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

from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
   browser = p.chromium.launch(headless=False)
   page = browser.new_page()
   page.goto('https://www.programsbuzz.com/search/node?keys=playwright+java')
   listOfElements = page.locator("//h3[@class='search-result__title']")
   expect(listOfElements).to_have_count(10)

The list has Ten items. Using the count assertion, we can verify that.

2. Nth content filter

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

from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
   browser = p.chromium.launch(headless=False)
   page = browser.new_page()
   page.goto('https://www.programsbuzz.com/search/node?keys=playwright+java')
   listOfElements = page.locator("//h3[@class='search-result__title']")
   eleText = listOfElements.nth(1).text_content()
   print(eleText)

3. Display a list of texts

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

from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
   browser = p.chromium.launch(headless=False)
   page = browser.new_page()
   page.goto('https://www.programsbuzz.com/search/node?keys=playwright+java')
   listOfElements = page.locator("//h3[@class='search-result__title']")
   eleText = listOfElements.all_text_contents()
   print(eleText)