Monday, March 31, 2025

Playwright - Various techniques to locate an element in web page.

 In Playwright, you can locate elements using various methods such as selectors, XPath, or text content. Here are some common ways to locate elements in Playwright:

Playwright - Various techniques to locate an element in web page.


1. Using CSS Selectors

Playwright supports standard CSS selectors to locate elements. Here's how you can locate an element using a CSS selector:


Syntax : 

// Locate an element using a CSS selector
const element = await page.$('css-selector');

Example :

const button = await page.$('button#submit');


2. Using XPath

XPath allows you to locate elements based on their hierarchical structure. You can use it when CSS selectors are not enough.


Example :

// Locate an element using XPath
const element = await page.$('//div[@class="my-class"]');

3. Using Text Content

You can also locate an element based on the visible text inside it.


Example :

// Locate an element based on its text content
const element = await page.$('text="Submit"');


4. Using page.locator()

For more flexibility and better handling of dynamic elements, Playwright provides the locator() method. This is often preferred for locating elements:


Example :

// Locate an element using a CSS selector
const element = page.locator('button#submit');


5. Waiting for Element

If you want to wait for an element to appear before interacting with it, you can use waitForSelector() or locator.waitFor():


Example :

// Wait for an element to appear using a CSS selector
await page.waitForSelector('button#submit');

// Wait for an element to appear using a locator
await page.locator('button#submit').waitFor();

6. Finding Multiple Elements

To locate multiple elements, you can use $$ (similar to querySelectorAll):


Example :

// Locate multiple elements with a given selector
const elements = await page.$$('div.item');

7. Finding Elements Inside Another Element

If you want to find an element inside another element, you can chain selectors:


Example :

// Locate an element inside another element
const parent = await page.$('.parent-class');
const child = await parent.$('.child-class');

This is all about various ways to interact with various elements in web page.


No comments:

Post a Comment