Rayrun

How do I use Playwright to retrieve information about the children of div elements on a webpage?

Answer

Fetching Child Elements of Divs with Playwright

You can use Playwright's $$eval method to fetch the children of divs. This method finds all elements matching a given selector and passes them as an array to a function.

Here's how you can get the number of children each div has:

const childCounts = await page.$$eval('div', (divs) => {
  return divs.map(div => div.children.length);
});

This will return an array with the number of children each div has.

For more complex operations, you can use a more detailed function in your $$eval call. For instance, if you want to get each child element's tag name and text content, you can do:

const childData = await page.$$eval('div', (divs) => {
  const data = [];
  for (const div of divs) {
    const childrenData = [];
    for (const child of Array.from(div.children)) {
      const textContent = child.textContent;
      const tagName = child.tagName;
      childrenData.push({ textContent, tagName });
    }
    data.push(childrenData);
  }
  return data;
});

This will return an array with arrays representing each div's children. Each inner array contains objects with each child element's tag name and text content.

In short, Playwright's $$eval method is a handy tool for fetching information about all elements matching a certain selector. You can pass in any function that takes in an array of Element objects and returns some value based on those elements.

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