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

混江龙づ霸主 提交于 2019-12-03 02:44:43
chridam

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();
});
bsides

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.

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