Automation with playwright - Part 2 Locating elements
Playwright: Locating Web Elements
Essential for performing actions (click, type, etc.) on web pages. Before any action, elements must be located/identified.
Locators
Locator object in playwright are the recommended way of selecting element and performing actions on them.
General Syntax:
await page.locator('selector').click();`
// await page.click('selector'); -> alternative
The selector can be of 3 types:
- Element Properties: Unique attributes like
id,name,class, ortag(e.g.,id=login). - CSS Selectors: (e.g.,
#loginusername,input[id="loginpassword"]). - XPath: (e.g.,
//button[@class="white"]).
Common Actions & Examples:
- Click:
.click() - Filling/Typing in Input Fields:
fill(): Clears input and types value.type(): Types value (does not clear, simulates key presses).
- Count:
.count() - Filter:
.filter({
has: page.locator('td'),
hasText: 'Product'
})
- Get nth item :
.nth().first().last()
Locating Multiple Web Elements
Using $$
Get an array of matching elements. Its actually a promise that will resolve to array of elementHandle objects. ElementHandle Functions
const elements = await page.$$('selector');
Iterating and Extracting Data:
const links = await page.$$('a'); // Get all anchor (link) tags
for (const link of links) {
const linkText = await link.textContent();
console.log(linkText);
}
Using locator
.locator() : When this matches multiple elements, we can choose which we want to work with. If we don’t the first matched element is used. Or we can get array
//returns array. each will be locator, but scope to one
locsArray = page.locator('div').all()
Locator Methods
find an element based on attributes
These are shortcuts to get locator objects, we can also write full xpaths.
page.getByAltText() // an element, usually image, by its text alternative.
page.getByPlaceholder() // an input by placeholder.
page.getByRole() // by explicit and implicit accessibility attributes.
page.getByText() // by text content.
page.getByLabel() // a form control by associated label's text.
page.getByTitle() // an element by its title attribute.
page.getByTestId() // an element based on its data-testid attribute.