DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Design Patterns for Scalable Test Automation Frameworks
  • Architecture Patterns : Data-Driven Testing
  • Selenium vs Cypress: Does Cypress Replace Selenium?
  • Getting Started With WebdriverIO Typescript Jasmine

Trending

  • Build Your First AI Model in Python: A Beginner's Guide (1 of 3)
  • Teradata Performance and Skew Prevention Tips
  • Java 23 Features: A Deep Dive Into the Newest Enhancements
  • A Guide to Container Runtimes
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Playwright Selectors and Locators: Everything You Need To Know

Playwright Selectors and Locators: Everything You Need To Know

In this article, unlock the power of Playwright selectors and locators with this comprehensive guide. Elevate your testing skills now.

By 
Yogesh Solanki user avatar
Yogesh Solanki
·
Jan. 30, 24 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
2.0K Views

Join the DZone community and get the full member experience.

Join For Free

Playwright is a powerful test automation framework that allows users to control web applications and conduct end-to-end test automation. In this article, we will try to cover complete functionality and the implementation of playwright selectors and locators.

Selectors act as a crucial component of the playwright framework. It helps automated tests to interact with web applications, like validating if that element exists on the web page or not, clicking on the available options, and providing inputs by typing or reading text. Playwrights come with multiple types of selectors and a good set of methods using which we can perform actions on selected elements.

A few of them are listed below:

CSS Selectors

When users locate Web elements using their attributes, IDs, classes, and more, they are widely used while performing test automation.

JavaScript
 
const element = await page.$('input[type="text"]');


JavaScript
 
const { chromium } = require('playwright'); 

(async () => {  const browser = await chromium.launch();  const page = await browser.newPage();  await page.goto('https://example.com');   // Find an element using a CSS selector  const element = await page.locator('h1');   // Interact with the element (e.g., click)  await element.click();   await browser.close(); })();


XPath Selectors

While identifying elements that do not have unique attributes or are nested elements, for these conditions, XPath is the most appropriate solution.

JavaScript
 
const element = await page.$x('//input[@type="text"]');


JavaScript
 
const { chromium } = require('playwright'); 

(async () => {  const browser = await chromium.launch();  const page = await browser.newPage();  await page.goto('https://example.com');   // Find an element using XPath  const element = await page.locator('//h1');   // Interact with the element (e.g., click)  await element.click();   await browser.close(); })();


Locator API

Locator API is a simplified way of locating web elements using chainable interfaces and performing actions on the selected elements.

JavaScript
 
const buttonLocator = page.locator('button'); await buttonLocator.click();


JavaScript
 
const { chromium } = require('playwright'); 

(async () => {  const browser = await chromium.launch();  const page = await browser.newPage();  await page.goto('https://example.com');   // Find an element by its attribute value  const element = await page.locator('[name="search"]');  // Interact with the element (e.g., type text)  await element.type('Playwright');   await browser.close(); })(); 


Text Selector

When users try to identify elements based on the visible text content of Element on the web page.

JavaScript
 
const element = await page.locator('text=Click Here');


JavaScript
 
const { chromium } = require('playwright'); 

(async () => {  const browser = await chromium.launch();  const page = await browser.newPage();  await page.goto('https://example.com');   // Find an element by its text content  const element = await page.locator('text=Welcome');   // Interact with the element (e.g., click)  await element.click();   await browser.close(); })();


Handling Shadow DOM

Playwright has the capability to identify and interact with elements that exist in Shadow DOM.

JavaScript
 
const shadowDomElement = await page.$('shadow-root-element >>> .shadow-element');


Waiting for Elements

Playwrights come with methods using which we can wait for the element to load, be visible, and meet any dependent condition before identifying and performing an action on it.

JavaScript
 
await page.waitForSelector('button', { state: 'visible' });


Selecting Options in Dropdowns

When a user needs to interact with menu options present in a drawdown, Playwright helps with these methods for performing the actions.

JavaScript
 
await page.selectOption('select#myDropdown', 'Option 1');


Selectors for Pop-Ups and Frames

Playwrights provide options to select elements from pop-up windows and iframes. Users can perform actions using these identified web elements.

JavaScript
 
const popup = await page.waitForPopup('https://example-popup.com'); const popupElement = await popup.$('div.popup-content');


Usage of Playwright Selectors

Playwright selectors play a vital role in performing automation-related tasks. We can perform element interaction (selecting, clicking, submitting web pages, and hovering over web elements), element verification (validating whether the element is visible, the element is present on the web page or not), data extraction (fetching text, files, and other data from the UI for further validation) and waiting for the web elements getting available on the UI.

What Is a Playwright Locator?

Playwright locators are a set of methods and APIs that allow you to select and interact with elements available on a web page. They provide a higher-level and more expressive way to locate elements compared to traditional selector types like CSS selectors and XPath.

Types of Playwright Locators

Playwright comes with multiple types of locators for identifying elements and fields on the web page.

  • Page.locator(): Users can use this while dealing with multiple elements on the web page. This method creates a locator for finding elements, and then we can chain multiple cations on the set of elements.
  • Locator.locator(): For refining selection further we can chain locator methods with existing locators.
  • locator.locatorAll(): For locating multiple elements matching a locator, we can use this method.

Locator Strategies

Locator strategies are used for selecting an appropriate locator for performing web automation few of them are listed below:

  • locator(‘text=Some Text’): Locating web elements based on the text visible.
  • locator(‘aria-label=Label’): Locating web elements based on the Aria label.
  • locator(‘aria-labelledby=ID’): Locating web elements based on the Aria labeled by ID.
  • locator(‘css selector’): For targeting elements based on CSS attributes, we need to combine the CSS selector with the locator.
  • locator(‘xpath selector’): For locating complex web elements and complex queries by combining an Xpath selector with a locator.

Implementation of Locator

JavaScript
 
const { chromium } = require('playwright'); 

(async () => {  const browser = await chromium.launch();  const page = await browser.newPage();  await page.goto('https://example.com'); 
  const locator = page.locator('text=Click Here');  await locator.click(); })();


Here, the first user is initializing the Chrome browser and then accessing a web URL; on this page, we are trying to locate the “Click here” button on the UI, using locator by text.

Playwright Locate Up-To-Date Elements

Whenever the locator is used to perform some action, an up-to-date DOM element is located on the page. So, in the code below, the highlighted element will be located two times. For the first time, it will be located before the hover action occurs, and for the second time, it will be located before the click action. This means that the new element corresponding to the locator will be used if the DOM changes in between the calls due to re-rendering. With this process, you will not be getting stale element exceptions like other automation tools and frameworks.

JavaScript
 
const locator = page.locator('text=Submit'); await locator.hover(); await locator.click();


End-to-End implementation of Playwright Selector and Locator

JavaScript
 
const { chromium } = require('playwright'); const { expect } = require('@playwright/test'); 

(async () => {  // Launch a browser  const browser = await chromium.launch();  const context = await browser.newContext(); 
  // Create a page  const page = await context.newPage();  await page.goto('https://example.com'); 
  // Use a locator to find an element by CSS selector  const searchInput = page.locator('input[type="text"]');   // Type text into the input field  await searchInput.type('Playwright'); 
  // Use a locator to find an element by text content  const welcomeMessage = page.locator('text=Welcome');   // Assert that the element with the text content exists  expect(await welcomeMessage.isVisible()).toBeTruthy(); 
  // Click on the element  await welcomeMessage.click(); 
  // Use a locator to find an element by XPath  const heading = page.locator('//h1'); 
  // Assert that the element with the XPath selector exists  expect(await heading.isVisible()).toBeTruthy(); 
  // Capture a screenshot  await page.screenshot({ path: 'example.png' }); 
  // Close the browser  await browser.close(); })();


In this example:

  1. We launch a Chromium browser (Chrome Browser) and create a new context and page.
  2. We use locators (Selector) to find elements on the page using CSS selectors, text content, and XPath.
  3. We are doing actions like typing into an input field, clicking on an element, and taking a screenshot.
  4. We are using assertions from `@playwright/test` (assuming you have it installed) to check if elements are visible.
  5. At the end, we close the browser.

Conclusion

In summary, Playwright’s selector and locator capabilities provide a powerful and flexible way to interact with web elements during automation and testing. They are designed to work with accuracy across different browsers and can adapt to various scenarios, making Playwright a valuable choice for web automation projects. However, it’s very important to select the most appropriate selector strategy based on your specific use case and application requirements for performing test automation with minimum failures.

Test automation Framework

Published at DZone with permission of Yogesh Solanki. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Design Patterns for Scalable Test Automation Frameworks
  • Architecture Patterns : Data-Driven Testing
  • Selenium vs Cypress: Does Cypress Replace Selenium?
  • Getting Started With WebdriverIO Typescript Jasmine

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!