← Back to Discord Forum

Get the text inside a ul list (that has a classname)

kombucha199posted in #help-playwright
Open in Discord

This is an image that shows what I'm trying to get-- the text inside the li class for each element in this list. How would I do this? Thanks!


This thread is trying to answer question "How to extract the text inside the li class for each element in a list?"

2 replies

Use .textContent() or just assert li to have some text with .toHaveText()


await page.locator('ul.pvs-list > li'); doesn't work, not sure what the issue is


Sure, let's dive into how you can use @playwright/test to extract text from each <li> element in a list.

First, you'll want to use the page.getByRole('listitem') method. This will locate all the <li> elements in your list.

const listItems = await page.getByRole('listitem');

Next, create an empty array where you'll store the text from each list item.

const texts = [];

Now, it's time to loop through each list item and extract the text. You can do this using the innerText() method.

for (const item of listItems) {
  const text = await item.innerText();

Finally, you can do whatever you need with the extracted texts. For instance, you might want to log them to the console.


Remember, this solution assumes that each <li> element in your HTML has a consistent role attribute. If your HTML structure is different or if there are other unique identifiers, you'll need to adjust the code.

Happy coding with @playwright/test!

Related Discord Threads

AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.