Playwright Understanding Playwright Locators and Assertions Estimated reading: 4 minutes 76 views In this guide on Understanding Playwright Locators and Assertions, I’ll help you master one of the most powerful aspects of Playwright: how it finds elements and how you can validate them with precision.What are Locators in Playwright?Locators are used to find and interact with elements on a page. Playwright offers a rich API that supports various selector types: Text: Targets elements by visible text. CSS: Targets elements using standard CSS selectors. Placeholder: Playwright can target inputs based on their placeholder attribute: XPath: allows for powerful hierarchical matching. Role: Playwright supports accessible roles like textbox, button, etc. Label: If the form has associated elements, you can target fields using their label textReal ExampleIn this example, we’ll interact with a modal form on the UI Elements Modals page by clicking the Open Form button. Once the modal appears, it reveals several address input fields.This setup provides a perfect real-world scenario to demonstrate how you can use different locator strategies in Playwright—such as text, placeholder, label, CSS selectors, roles, and XPath—to reliably find and interact with elements on the page.1. Text LocatorText: Open Form Buttonconst openFormButton = page.locator('text=Open Form'); await openFormButton.click();This clicks the Open Form button by its exact text.2. CSS SelectorCSS Selector: Address 1 & 2await page.fill('#address1', '123 Main St'); await page.fill('#address2', 'Apt 4B');Here, the #address1 and #address2 are id attributes of the input fields, making them perfect for CSS-based selectors.3. Placeholder TextPlaceholder: Enter your addressawait page.getByPlaceholder('Enter your address').fill('123 Main St'); await page.getByPlaceholder('Address Line 2').fill('Apt 4B');This approach is highly readable and ideal when ids or classes are dynamic or missing.4. Label TextLabel Text: Address Line 1 & Address Line 2await page.getByLabel('Address Line 1').fill('123 Main St'); await page.getByLabel('Address Line 2').fill('Apt 4B');This makes tests more resilient and semantically meaningful.5. Role-Based LocatorRole Based Locator: Open Form Buttonawait page.getByRole('button', { name: 'Open Form' }).click();Great for targeting elements based on accessibility best practices.6. XPath SelectorXPath: Locating Address 1await page.fill('//input[@id="address1"]', '123 Main St');Use this when dealing with complex or deeply nested elements. Pro TipFor better test stability and clarity, prioritize getByRole, getByLabel, and getByPlaceholder — these are more semantic, accessible, and less likely to break when the UI changes.Bringing It All TogetherLet’s bring all the locator strategies together and run a complete example using the registration form on the UI Elements Modals page.In this form, we’ll interact with inputs like email, password, address, city, and more—using a mix of Playwright locator techniques such as getByLabel, getByPlaceholder, CSS selectors, XPath, and getByRole. This real-world example shows how versatile and intuitive Playwright can be for form automation.Demo Test Scriptconst { test, expect } = require('@playwright/test'); test('fill and submit registration form using mixed locators', async ({ page }) => { //Visit the page containing the form await page.goto('https://jahmalrichard.github.io/mqa-demo-test-app/ui-elements-modals.html'); // Click the "Open Form" button using text locator await page.click('text=Open Form'); // Email - located by label await page.getByLabel('Email').fill('john.doe@masteringqa.com'); // Password - located by ID (CSS) await page.fill('#inputPassword4', 'SuperSecure123'); // Address - located by placeholder await page.getByPlaceholder('1234 Main St').fill('456 Ocean Drive'); // Address 2 - located by label await page.getByLabel('Address 2').fill('Apt 101'); // City - located by XPath await page.fill('//input[@id="inputCity"]', 'Miami'); // State - use label and select by visible text (if options exist) const stateDropdown = page.locator('#inputState'); await expect(stateDropdown).toBeVisible(); await stateDropdown.selectOption({ label: '...' }); // Zip - located by label await page.getByLabel('Zip').fill('33101'); // Submit the form using role-based locator on button await page.getByRole('button', { name: 'Submit' }).click(); });Best Practices for Locators in Playwright 1. Attributes Use data-testid attributes for stable and reliable selectorsCustom test IDs like data-testid="submit-button" are unaffected by visual changes and help keep your tests clean and maintainable. 2. Semantic Locators Prefer semantic locators like getByRole, getByLabel, or getByPlaceholderThese mimic how real users interact with the page, improve accessibility, and make your tests more intuitive. 3. Avoid Brittle XPaths Avoid brittle XPath selectors unless there's no better optionXPath can break easily with small DOM changes. Use it only when you can’t target an element by role, text, or ID. 4. Check for Visibility Always check for visibility before interactingBefore clicking or typing, use assertions like expect(locator).toBeVisible() to avoid flaky tests. 5. Scope Locators Scope locators within containers to avoid ambiguityWhen dealing with repeated elements (e.g., in modals or lists), use scoped locators to pinpoint the correct one and reduce selector conflicts.Common Assertions in PlaywrightAssertions ensure your test outcomes match expectations. Playwright includes built-in assertion methods:Common Playwright Assertionsawait expect(page.locator('.notification-success')).toContainText('Success!'); await expect(page).toHaveURL(/ui-elements-modals.html/); await expect(page.locator('h2').filter({ hasText: 'Modals' })).toBeVisible(); await expect(page.locator('#userbox')).toBeVisible();Handling Waits AutomaticallyOne of Playwright’s killer features is automatic waiting. There’s no need to add sleep or wait statements. Playwright waits for elements to be actionable.ConclusionMastering Playwright Locators and Assertions is key to writing tests that are both reliable and readable. Up next, we’ll tackle real-world challenges in Handling Authentication and Sessions in Playwright. Playwright - Previous Writing Your First Playwright Test Next - Playwright Handling Authentication and Sessions in Playwright