Finding elements using XPath
XPath is a language to query XML-like documents. Remember how we said that HTML was a relaxed kind of XML? This means that we could navigate through the DOM using some kind of XML query language such as XPath.
Before digging into XPath's selectors, if you want to try XPath queries, Chrome DevTools includes a set of functions you can use inside the developer tools Console tab (https://hardkoded.com/ui-testing-with-puppeteer/console). One of these functions is $x
, which expects an XPath expression and returns an array of elements:
If you open the Console tab on any page, you can run $x('//*')
to test the //*
selector.
To better understand an XPath expression, you need to see your HTML as XML content. We are going to navigate this XML document from the very same root, the HTML attribute.
Select from the current node
Selector: //
. This means "From the current...