How to use CSS selectors to locate elements in Puppeteer?

In Puppeteer, you can use CSS selectors to locate elements in the DOM just like you would in a browser's developer tools.

Here's an example of how you can use CSS selectors to locate elements in Puppeteer:

  1. Start by launching a new browser and creating a new page:
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); // Your code here await browser.close(); })();
  1. Use the page.$() method to locate an element using a CSS selector. This method accepts a CSS selector as a parameter and returns the first element that matches the selector:
const element = await page.$('h1');
  1. You can also use the page.$$() method to locate multiple elements that match a CSS selector. This method returns an array of all elements that match the selector:
const elements = await page.$$('p');
  1. Once you have located an element, you can interact with it using Puppeteer's API, such as clicking on it, typing text into it, or extracting its attributes or text content:
await element.click();

Here's an example of locating an element by its class name and clicking on it:

const element = await page.$('.my-element-class'); await element.click();

Keep in mind that using CSS selectors to locate elements in Puppeteer is similar to using JavaScript in a browser's developer tools, so you can use any valid CSS selector syntax to locate elements on a page.