How to get a collection of elements with playwright?
Solution 1
I have already found the answer. Need to use page.$$(selector)
instead of page.$(selector)
to grab like document.querySelectorAll(selector)
.
Solution 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);
Here is a link to the page.evaluate official documentation
Solution 3
- for playwright use: await page.$$(selector);
CoderDesu
Software engineer. Primary stack related to JavaScript ecosystem (TypeScript, React, Node, Express, Nest(not Next), Jest). Also have experience with Python3, Bash. Interested in exploring Rust language. Continiously broad my fundamental knowledge and skills in Software development and related fields.
Updated on July 09, 2022Comments
-
CoderDesu almost 2 years
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
-
Mithun Shreevatsa over 2 years@EugZ- how about the length?
-
Kirti Chaturvedi over 2 yearsfor length use .length .For e.g: const counts = await page.$$(selector); expect(counts.length).toBe(3)