Puppeteer - Xpath Axes



To determine an element uniquely, we can either take the help of any of the attributes within the html tag or we can use a combination of attributes on the html tag. Mostly the id attribute is used since it is unique to a page.

However, if the id attribute is not present, we can use other attributes like the class, name, and so on. In case the attributes like id, name, and class are not present, we can utilise a distinct attribute available to only that tag or a combination of attributes and their values to identify an element.

For this, we have to use the xpath expression. Also, if the element on a page is dynamic, then xpath selector can be a good choice as a selector.

The xpath is bi-directional which means we can traverse from the parent to the child element and also from the child to the parent element. The details of xpath axes shall be available in the below link −

https://www.tutorialspoint.com/xpath/xpath_axes.htm

In the below image, let us identify the highlighted edit box and obtain the value of its class attribute - gsc-input.

Highlighted Edit Box

In the above example, there are two columns (represented by td tags) in the table having the tr tag as their parent. The input box is present in the first column.

So the xpath expression shall be as follows −

//table/tbody/tr/child::td.

Here, we are working with the xpath selector, so we have to use the method: page.$x(xpath value). The details on this method are discussed in the Chapter of Puppeteer Locators.

To begin, follow Steps 1 to 2 from the Chapter of Basic Test on Puppeteer which are as follows −

Step 1 − Create a new file within the directory where the node_modules folder is created (location where the Puppeteer and Puppeteer core have been installed).

The details on Puppeteer installation is discussed in the Chapter of Puppeteer Installation.

Right-click on the folder where the node_modules folder is created, then click on the New file button.

Node Modules

Step 2 − Enter a filename, say testcase1.js.

Testcase1.JS

Step 3 − Add the below code within the testcase1.js file created.

//Puppeteer library
const pt= require('puppeteer')
async function selectorAxesXpath(){
   //launch browser in headless mode
   const browser = await pt.launch()
   //browser new page
   const page = await browser.newPage()
   //launch URL
   await page.goto('https://www.tutorialspoint.com/index.htm')
   //identify element with xpath axes
   const n = (await page.$x("//table/tbody/tr/child::td"))[0]
   // get value of class attribute
   let v = await page.$eval("input", n => n.getAttribute("class"))
   console.log(v)
}
selectorAxesXpath()

Step 4 − Execute the code with the command given below −

node <filename>

So in our example, we shall run the following command −

node testcase1.js
node_testcase1.jpg

After the command has been successfully executed, the value of the class attribute for the element - gsc-input gets printed in the console.

Advertisements