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.
- Panic: runtime error: index out of range [3] with length 3
- Pkdrawing
- Python strftime microseconds 3 digits
- Package ‘libzip’, required by ‘virtual:world’, not found
- Php static anonymous function
- Pandas read_sql slow
- Property ‘pipe’ does not exist on type ‘readablestream
‘ - Parsing error: cannot read file ‘tsconfig.json’
- Partial credentials found in env, missing: aws_secret_access_key
- Playwright get table rows