What is the Puppeteer equivalent of document.querySelectorAll()?
Benjamin C
benjamin c profile pic

The Puppeteer equivalent ofdocument.querySelectorAll() ispage.$$(). Here's a detailed explanation: 1. Launching a new browser instance and creating a new page:

1
2
3
4
5
6
7
8
9
10
11
12
13

   const puppeteer = require('puppeteer');

   (async () => {
     const browser = await puppeteer.launch();
     const page = await browser.newPage();

     // Perform actions with the page here

     // Close the browser
     await browser.close();
   })();
   

This code sets up a basic Puppeteer script. It launches a new headless browser instance and creates a new page to work with. 2. Selecting multiple elements usingpage.$$(): To select multiple elements on a page in Puppeteer, you can use thepage.$$() method. It takes a CSS selector as an argument and returns an array ofElementHandle instances representing the matched elements.

1
2
3

   const elements = await page.$$('yourSelector');
   

In this example,page.$$() is called with the CSS selector'yourSelector'. The method returns a promise that resolves to an array ofElementHandle instances representing the matched elements. Replace'yourSelector' with the actual CSS selector you want to use to select the elements on the page. 3. Accessing properties and manipulating the selected elements: Once you have selected the elements usingpage.$$(), you can access their properties, perform actions, or extract data from them using Puppeteer's available methods and functions.

1
2
3
4
5
6
7

   for (const element of elements) {
     const textContent = await element.getProperty('textContent');
     const value = await textContent.jsonValue();
     console.log(value);
   }
   

In this code snippet, afor...of loop is used to iterate over theElementHandle instances in theelements array. ThegetProperty() method is called on each element to access itstextContent property. Then, thejsonValue() method is used to extract the value of the property as a JSON representation. Finally, the extracted value is logged to the console. By following these steps, you can use Puppeteer'spage.$$() method as the equivalent ofdocument.querySelectorAll() to select multiple elements on a page. This allows you to work with the selected elements and perform various actions, extract data, or manipulate the DOM as needed within your Puppeteer scripts.