Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a collection of elements with playwright?

How to get all images on the page with playwright? I'm able to get only one (ElementHandle) with following code, but not a collection.

const { chromium } = require("playwright");

class Parser {
  async parse(url) {
    const browser = await chromium.launch();
    const page = await browser.newPage();
    await page.goto(url);
    await page.waitFor("img");
    // TODO: get somehow collection of elements
    return await page.$("img");
  }
}

module.exports = Parser;

Somewhere in another module far far away:

const Parser = require("./path/to/dir/Parser.js");
const parser = new Parser();

parser
    .parse(body.url)
    .then(elemHandle => {
      // here I get only one ElementHandle object, but suppose to get an array or collection
    })
    .catch(err => {
      throw new Error(err);
    });

Node v.12.16.1

like image 692
EugZ Avatar asked Apr 27 '20 07:04

EugZ


4 Answers

I have already found the answer. Need to use page.$$(selector) instead of page.$(selector) to grab like document.querySelectorAll(selector).

like image 156
EugZ Avatar answered Oct 31 '22 08:10

EugZ


As mentioned in the accepted answer, you can use await page.$$(selector). Here is a link to the page.$$ official documentation

You can also use the following code.

const result = await page.evaluate(selector => document.querySelectorAll(selector) , selector);

Here is a link to the page.evaluate official documentation

like image 34
Shubham Sharma Avatar answered Oct 31 '22 08:10

Shubham Sharma


  • for playwright use: await page.$$(selector);
like image 21
Med Bechir Said Avatar answered Oct 31 '22 10:10

Med Bechir Said


There is another way to work with a list of elements you can read from the documentation. And I like it much more https://playwright.dev/docs/locators#lists

So you just select using the page.locator and after that, you can interact with each element using for loop or selected the needed element using .nth()

like image 23
Igor Nosovsky Avatar answered Oct 31 '22 10:10

Igor Nosovsky