'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
Solution 1:[1]
I have already found the answer. Need to use page.$$(selector)
instead of page.$(selector)
to grab like document.querySelectorAll(selector)
.
Solution 2:[2]
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);
Solution 3:[3]
- for playwright use: await page.$$(selector);
Solution 4:[4]
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | EugZ |
Solution 2 | Charley Rathkopf |
Solution 3 | Med Bechir Said |
Solution 4 | Igor Nosovsky |