Puppeteer check if selector exists

Sure! Here’s an example of the HTML content in a `

` element without the ``, `

`, and `` tags:

“`html

This is an example of HTML content inside a div.

“`

In this example, we are using Puppeteer to check if a selector exists on a specific web page. Puppeteer is a Node library which provides a high-level API for controlling headless Chrome or Chromium browsers.

To use Puppeteer, you need to install it as a dependency in your project by running `npm install puppeteer` in your terminal.

Once installed, you can launch a headless Chrome browser using `puppeteer.launch()` and open a new page with `browser.newPage()`. Then, you can navigate to a specific URL using `page.goto()`.

To check if a selector exists, we use `page.waitForSelector()` to wait until the selector appears in the page before proceeding. Then, we can use `page.$()` with the same selector to get the element with that selector. If the element exists, `page.$()` will return a non-null value, indicating that the selector exists on the page.

In the example, we are checking if the selector with class `example-selector` exists on the page of `https://example.com`. The result is stored in the `isSelectorExist` variable. If `isSelectorExist` is true, we log “The selector exists!” to the console; otherwise, we log “The selector does not exist!”.

Finally, we close the browser using `browser.close()`.

Leave a comment