In Playwright, if you want to handle multiple elements using a single locator, you can interact with them as a group or iterate through them. In Playwright, handling multiple elements involves locating them using selectors and then performing actions or assertions on each element. Below are common approaches to handle multiple elements, with concise explanations and examples.
Example for Multiple element handling
In this example we are fetching multiple options for select dropdown in playwright with different type of locator approach.
1. Handle multiple element using locator
In this example we fetching multiple options for select dropdown using locator() function in playwright.
// @ts-check import { test, expect } from '@playwright/test'; test("Handle multiple element using locator", async ({ page }) => { await page.goto("https://practice.expandtesting.com/dropdown"); await page.waitForSelector("[id='country']"); const items = await page.locator("[id='country'] option"); const count = await items.count() ; for (let i = 0; i < count; i++) { const text = await items.nth(i).textContent(); console.log(`Item ${i + 1}: ${text}`); } });
const items = page.locator('[id='country'] option');
const allItems = await items.all(); for (const item of allItems) { const text = await item.textContent(); console.log(text); }
2. Handle multiple element using page.$$
In this example we fetching multiple options for select dropdown using page.$$() function in playwright.
// @ts-check import { test, expect } from '@playwright/test'; test("Handle multiple element using page.$$", async ({ page }) => { await page.goto("https://practice.expandtesting.com/dropdown"); await page.waitForSelector("[id='country']"); const items = await page.$$("[id='country'] option"); for (const element of items) { const text = await element.textContent(); console.log(`Item : ${text}`); } });
3. Handle multiple element using allTextContents() function
In this example we fetching multiple options for select dropdown using allTextContents() function in playwright.
// @ts-check import { test, expect } from '@playwright/test'; test.only("Handle multiple element using allTextContents() function", async ({ page }) => { await page.goto("https://practice.expandtesting.com/dropdown"); await page.waitForSelector("[id='country']"); const items = await page.locator("[id='country'] option").allTextContents(); for (const item of items) { console.log(`Item : ${item}`); } });
You can handle multiple element using above techniques
Best Practices
- Use Locators: Prefer page.locator() over page.$$ for better performance and auto-waiting.
- Narrow Selectors: Use specific selectors to avoid unintended matches (e.g., .container .item instead of .item).
- Error Handling: Handle cases where no elements are found or elements are not interactable.
- Debugging: Use page.pause() or locator.highlight() to inspect elements during development.
No comments:
Post a Comment