In Playwright, you can use the nth selector to match elements based on their position in a list or sequence. This is often used with CSS selectors to target specific elements when they follow a predictable pattern or order.
In CSS, the :nth-child() or :nth-of-type() pseudo-classes are used to select elements based on their position within a parent element. Playwright provides a way to use these pseudo-classes in combination with its locator API.
Here’s an example of how to use nth-child in Playwright:
in this example trying to locate position 2 of the element using nth-child CSS locator.
// Import Playwright const { chromium } = require('playwright'); (async () => { const browser = await chromium.launch(); const page = await browser.newPage(); await page.goto('https://www.w3schools.com/TAGs/tryit.asp?filename=tryhtml_list_test'); // Select the 2nd <li> element inside a <ul> const secondItem = await page.locator('ul li:nth-child(2)'); await browser.close(); })();
Example with nth-of-type
You can also use :nth-of-type if you want to target the nth element of a particular type (e.g., all <div> elements).
// Import Playwright const { chromium } = require('playwright'); (async () => { const browser = await chromium.launch(); const page = await browser.newPage(); await page.goto('https://skptricks.github.io/learncoding/selenium-demo/login%20registration%20page/Register.html'); // Select the 3rd <li> element inside a <ul> const thirdItem = await page.locator('form input:nth-of-type(3)'); await browser.close(); })();
Sometimes, you might want to dynamically calculate or pass the index (for example, iterating through elements or picking the nth item based on some condition). You can pass variables to Playwright locators for this.
const itemIndex = 4; // Dynamic index const item = page.locator(`ul li:nth-child(${itemIndex})`); await item.click();
No comments:
Post a Comment