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.
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.
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();
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.
If you still have questions, please ask a question and I will try to answer it.
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].