How to check if element exists in a Webpage – Puppeteer

puppeteer

Puppeteer is a versatile library that serves various purposes, such as testing, web scraping, and automation. It empowers you to interact with web pages and extract valuable data through selectors. While Puppeteer offers numerous helpful APIs, it lacks a built-in method for checking the existence of a selector.

Method:

To check whether an element exists on a webpage, you can use the waitForSelector method of page object. This method will raise an error if the element being waited for does not exist within the specified timeout. That’s why it is important to handle the error properly else the javascript whole execution might stop.

The function would resemble the following:

async function checkIfElementExists(page, selector) {
  try {
    await page.waitForSelector(selector, { timeout: 5000 }); // you can adjust the timeout
    return true;
  } catch (error) {
    console.log(`Element with selector ${selector} does not exists`);
    return false;
  }
}

Remember to await the function when calling it. It will return true if the element is found and false if the element does not exists which is determined by the waitForSelector method.

Leave a Reply

Your email address will not be published. Required fields are marked *