Rayrun
← Back to Discord Forum

Playwright's equivalent of Selenium's By class

Hi all,

I'm making a change from Selenium to Playwright and I was wondering what's Playwright equivalent of By class. For example, in Selenium I had locators defined like this (picture). What's the best practice to do the same thing with Playwright. Much appreciate any advice.

2023-07-21_23_45_39-Svea.QA.Template_-_Microsoft_Visual_Studio.jpg

This thread is trying to answer question "What is the equivalent of Selenium's By class in Playwright?"

0 replies

Answer

Locating Elements with Playwright

Playwright's Locator class is your go-to tool for finding elements on a webpage. It's similar to Selenium's By class and offers various methods to locate elements.

Using CSS Selectors

You can use CSS selectors to find elements. Here's how you can locate an element with a specific class name:

const element = await page.locator('.my-class').first();

In this code, .my-class is the CSS selector for elements with the class name "my-class". The .first() method selects the first matching element.

Using XPath Expressions

If you prefer XPath expressions, you can use them too. Here's how you can locate a <div> element with a specific class name:

const element = await page.locator('//div[@class="my-class"]').first();

Using Text Content

Playwright also allows you to locate elements using text content. For instance, to find an input field to the right of a specific text label, you can use:

const inputElement = await page.locator('input:right-of(:text("Label"))').first();

In this code, 'input:right-of(:text("Label"))' selects <input> elements to the right of text containing "Label".

Playwright provides flexible options for locating elements, making it easy to interact with them during automated testing or web scraping tasks. For more insights on using Playwright, check out Mastering Playwright Test Automation: Your Comprehensive Cheat Sheet.

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].