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
I have already found the answer. Need to use page.$$(selector)
instead of page.$(selector)
to grab like document.querySelectorAll(selector)
.
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With