Rayrun

How can I use Playwright to retrieve the text from each <li> element in a list?

Answer

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();
  texts.push(text);
}

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

console.log(texts);

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!

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

TwitterGitHubLinkedIn
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.