Like any other automation tool, locators and selectors are pretty standard when writing tests with them. Locators are used to performing actions on elements of a page through methods such as click, type, assert, etc. Selectors are strings that are used to make up a locator.
The playwright can handle both CSS and XPATH selectors.
Playwright Using CSS:
- CSS engine pierces open shadow DOM by default, and the playwright adds custom pseudo-classes like :visible, :text, etc.
const {test, expect} = require('@playwright/test');
test('CSS Selector', async ({page})=>
{
await page.goto("https://www.programsbuzz.com/");
await page.locator('.gv-icon-52').click()
await page.locator('#edit-keys').type('Playwright')
await page.locator('#edit-submit').click()
});
- So we navigated to the page, clicked on search, typed in 'Playwright,' and clicked on submit using the CSS selector.
- A dot followed by the class value is viable for using the class.
- In the case of ID, we can use # followed by the ID value present in the DOM.
Playwright Using XPATH:
- XPATH selectors are equivalent to calling document.evaluate.
- // and .. can be an early indicator of the XPath selector which is being utilized.
- Playwright works in the fashion of converting '//HTML/body' to 'xpath=//html/body'.
- Like CSS, XPATH cannot pierce shadow roots.
const {test, expect} = require('@playwright/test');
test('CSS Selector', async ({page})=>
{
await page.goto("https://www.programsbuzz.com/");
await page.locator("//i[@class='gv-icon-52']").click()
await page.locator("//input[@id='edit-keys']").type('Playwright')
await page.locator("(//input[@id='edit-submit'])[1]").click()
});
- // followed by the tag name and attribute name within a square bracket, and its value is the apparent syntax of XPATH.
- The third selector chooses the id element by its index position.