问题
Using Puppeteer, I would like to get all the elements on a page with a particular class name and then loop through and click each one
Using jQuery I can achieve this with
var elements = $("a.showGoals").toArray();
for (i = 0; i < elements.length; i++) {
$(elements[i]).click();
}
How would I achieve this using Puppeteer?
Update
Tried out Chridam's answer below but I couldn't get to work (though answer helpful so thanks due there) so I tried the following and this works
await page.evaluate(() => {
let elements = $('a.showGoals').toArray();
for (i = 0; i < elements.length; i++) {
$(elements[i]).click();
}
});
回答1:
Use page.evaluate to execute JS:
const puppeteer = require('puppeteer');
puppeteer.launch().then(async browser => {
const page = await browser.newPage();
await page.evaluate(() => {
let elements = document.getElementsByClassName('showGoals');
for (let element of elements)
element.click();
});
// browser.close();
});
回答2:
To get all elements, you should use page.$$ method, which is the same as [...document.querySelectorAll]
(spread inside an array) from reqular browser API.
Then you could loop through it (map, for, whatever you like) and evaluate each link:
const getThemAll = await page.$$('a.showGoals')
getThemAll.map(link => {
await page.evaluate(() => link.click())
})
Since you also want to do actions with the things you got, I'd recommend using page.$$eval which will do the same as above and run an evaluation function afterwards with each of the elements in the array in one line. For example:
const clickThemAll = await page.$$eval('a.showGoals', links => links.map(link => link.click())
To explain the line above better, $$eval
returns an array of links, then it executes a function with the links as an argument then it runs through every link via map method.
Check the official documentation too, they have good examples there.
来源:https://stackoverflow.com/questions/48673906/collect-elements-by-class-name-and-then-click-each-one-puppeteer