Filter elements using Puppeteer

Let's assume that you want to filter some elements using Puppeteer.

As an example, we'll filter links on a website which have href equal to a certain string:

javascript
// Defining the string to filter the results
let urlToFilter  = 'https://elonmusk.com';

// Getting all the <a></a> elements of a website
let urlsToVisit  = await page.$$eval('a', (links, urlToFilter) => links.map(link => link.href).filter(link => link.startsWith(urlToFilter)), urlToFilter);  

Remember that you need to pass the variable to filter as an argument to the page.$$eval() function. Otherwise, the variable will be defined in the Node context but it'll be undefined in the browser context (you won't filter the results).

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.