In this lesson from the "Test Guild UI Automation with Playwright" course, Artem Bondar explains how to use the Locator method to find web elements on a page. Here's what you'll learn:

1. **Introduction to Locator Syntax Rules**:
- **Overview**: Understand the importance of locating elements using Playwright and the various methods available to find elements by ID, attribute, tag, and more.

2. **Locating Elements by Different Methods**:
- **By Tag Name**: Use `page.locator('input')` to find elements by tag name. This will return all elements with the specified tag.
- **By ID**: Use `page.locator('#inputEmail1')` to find an element by its ID. Prefix the ID with a hash (`#`).
- **By Class Value**: Use `page.locator('.shape-rectangle')` to find elements by class value. Prefix the class with a dot (`.`).
- **By Attribute**: Use `page.locator('[placeholder="Email"]')` to find elements by attribute. Use square brackets (`[]`) around the attribute.
- **By Entire Class Value**: Use `page.locator('[class="input full-width size-medium status-basic shape-rectangle nb-transition"]')` to find elements by the full class value.
- **Combining Selectors**: Combine different selectors for a more specific match, e.g., `page.locator('input[placeholder="Email"]')`.
- **By XPath**: Although not recommended, you can use XPath with `page.locator('//*[@id="inputEmail1"]')`.

3. **Working with Locator Results**:
- **Handling Multiple Matches**: Understand that locators return all matching elements, and Playwright needs a unique match to perform actions. Use `locator.first()` to act on the first match.
- **Triggering Actions**: Learn that Playwright performs actions on elements only when triggered. For example, use `await page.locator('#inputEmail1').click()` to click an element.

4. **Practical Examples**:
- **Running Tests**: Run tests in UI mode to see actions performed and errors logged. Understand how Playwright handles multiple matches and suggests unique locators.

5. **Summary of Locator Syntax Rules**:
- **Tag Name**: Use the tag name directly.
- **ID**: Prefix with `#`.
- **Class**: Prefix with `.`.
- **Attribute**: Use square brackets (`[]`).
- **Combining Selectors**: Combine multiple selectors for specificity.
- **XPath**: Use cautiously as it is not recommended.
- **Text Matching**: Use `:text` for partial matches and `:text-is` for exact matches.

By the end of this lesson, you will be adept at using Playwright’s Locator method to find web elements effectively and understand the syntax rules for different types of locators. This foundational knowledge will help you build reliable and maintainable test scripts. See you in the next lesson!

Comments are closed.

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}