Playwright XPath Selectors

Playwright XPath Selectors

In playwright, we can identify and track down elements present on the webpage with two methods, one by CSS and another by Xpath. Xpath is also used to identify and track down elements present on the DOM but is slightly not good than CSS when tracking our locators intensely.

  • Xpath does not pierce the shadow roots of the DOM as CSS.
  • The Selectors starting with // and .. are usually assumed to be XPath.
  • It converts '//html/body' to 'xpath=//html/body'.
  • Xpath is nothing but a locator and an address inside the HTML doc.
  • Playwright supports every typically used XPath function, pretty much everything.

Let us see an example.

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()
});

use xpath in playwright

  • We can see that we have used the Xpath syntax to locate the DOM elements and automate them.
  • // followed by tag name and attribute followed by "@" and value of it is the syntax of XPath.
Tags
Standard (Image)