Collect elements by class name and then click each one - Puppeteer

…衆ロ難τιáo~ 提交于 2019-12-20 09:58:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!