LingeringDogSponge
LingeringDogSponge

Reputation: 67

How do I loop through a puppeteer selector response?

So, with page.evaluate I could do:

await page.evaluate(function() {
   var links = document.querySelectorAll('a');
   for (var i = 0; i < links.length; i++) console.log(links[i].href);
});

However I would like to do this with page.$$ and I'm unsure how you would do this. I'm trying to do everything without the need for page.evaluate because it seems entirely unnecessary. Puppeteer has lots of cool gadgets I'm trying to get a grasp with.

Upvotes: 0

Views: 353

Answers (1)

pavelsaman
pavelsaman

Reputation: 8332

The documentation for what you're looking for is here: https://github.com/puppeteer/puppeteer/blob/v5.4.1/docs/api.md#pageselector-1 You can take that example and adjust it to your needs.

It'd be:

const linksHrefs
    = await page.$$eval('a', links => links.map(link => link.getAttribute('href')));
console.log(linksHrefs);

Upvotes: 3

Related Questions