YouTip LogoYouTip

Playwright Locators

Locator is one of the core concepts in Playwright, representing a way to find elements on a page. This chapter introduces Playwright's recommended positioning methods: locating elements by role, text, label, and placeholder. * * * ## What is Locator Locator is an abstract object used by Playwright to find elements on a page. Unlike traditional `document.querySelector()`, Playwright's Locator has automatic waiting and automatic retry capabilities. When the page content changes dynamically, the Locator will continuously re-search for elements until it finds a matching element or times out. ## Example // Create a Locator (at this point, the element is not immediately searched) // Execute the operation, Playwright will automatically wait for the button to appear and become actionable await button.click(); ### How Locator Works When creating a Locator, Playwright only records a search rule. When you call operations like `.click()`, `.fill()` or assertions like `expect(locator)`, the Locator truly starts searching for elements. If it cannot find the element, the Locator will keep retrying until the operation times out. * * * ## Locate by Role: getByRole() `getByRole()` is the most recommended positioning method in Playwright. It finds elements through the element's accessibility role (ARIA Role), which is the closest to how users perceive elements. ### Basic Usage ## Example // Locate a button - by role "button" const submitBtn = page.getByRole('button',{ name:'submit'}); await submitBtn.click(); // Locate a link - by role "link" const homeLink = page.getByRole('link',{ name:'Home'}); await homeLink.click(); // Locate a heading - by role "heading" const mainTitle = page.getByRole('heading',{ name:'Welcome to TUTORIAL'}); // Locate a textbox - by role "textbox" const searchBox = page.getByRole('textbox',{ name:'Search'}); await searchBox.fill('Playwright'); ### Common ARIA Roles | Role | Corresponding HTML Element | Usage Example | | --- | --- | --- | | `'button'` | `
← Playwright ActionsPlaywright Project Structure β†’