XPath stands for XML Path. It is W3C recommended technique used to identify and navigate nodes in an XML document. In automation, we use XPath to find elements on a webpage. Like any other language, Playwright supports XPath Selector and all its techniques and functions.
XPath selectors are equivalent to calling Document.evaluate(), where evaluate() is a method of the Document interface that selects elements based on the XPath expression given in parameters.
Note: XPath does not pierce shadow roots.
Let us check out how we can use XPath selectors in playwright java.
Use the locator method inside double quotes in java.
A selector starting with a double forward slash (//) or double dots (..) is assumed to be an XPath selector.
We will use the XPath selector for the demo to sign in with the username.
page.navigate("https://www.programsbuzz.com/user/login"); page.locator("xpath=//input[@id= 'edit-name']").type("Naruto");
page.navigate("https://www.programsbuzz.com/user/login"); page.locator("//input[@id= 'edit-name']").type("Naruto");
"Xpath=" is entirely optional.
A single slash "xpath=" is necessary; without this, it will throw an error.
With XPath indexing:
Sometimes there is a need to fetch an element from many other similar elements. This time, we can use the indexing option to bring by order the element located.