Playwright how to check if element exists

Playwright – How to Check if Element Exists

When working with Playwright, you can check if an element exists on a web page by using the page.waitForSelector() function. This function waits for an element matching the specified selector to appear in the DOM, and returns a promise that resolves to the element handle.

Here’s an example:

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');

  try {
    await page.waitForSelector('#myElement', { timeout: 5000 });
    console.log('Element exists');
    // Do something with the element
  } catch (error) {
    console.log('Element does not exist');
  }

  await browser.close();
})();
  

In this example, we first launch a Chromium browser and open a new page. We then use the page.waitForSelector() function to wait for an element with the ID myElement to appear on the page. If the element exists, the code inside the try block will be executed, indicating that the element exists. If the element does not appear within the specified timeout (in this case, 5 seconds), a TimeoutError will be thrown, and the code inside the catch block will be executed.

You can replace #myElement with any valid CSS selector to match the element you’re looking for. Playwright supports various types of selectors, such as ID, class, attribute, or XPath selectors.

Leave a comment