×
☰ See All Chapters

Group index in xpath

Retrieving one element from a group of matching elements by using index is called group index. When the xpath expression matches with multiple elements, then we go for group index. In Group index, we write xpath expression within the braces and then we write the index outside the braces. Internally, it executes the xpath expression first and stores the result in an xpath array whose index starts with 1.  last() is a function that is used to retrieve the last element present in the xpath array.  position() is a function that is used to retrieve the position of element in the xpath array.

Syntax:

(xpath expression)[index]

Considering the below sample html code, below are the different xpath examples using group index

<html>

</head>

<body>

        <table>

                <tr>

                        <td><input type="text" value="A"></td>

                        <td><input type="text" value="B"></td>

                </tr>

                <tr>

                        <td><input type="text" value="C"></td>

                        <td><input type="text" value="D"></td>

                </tr>

        </table>

</body>

</html>

 

Xpath using group index

Matching element

//input

ABCD

(//input)[1]

A

(//input)[2]

B

(//input)[3]

C

(//input)[4]

D

(//input)[last()]

D

(//input)[last()-1]

C

//input[1]

AC

(//input[1])[1]

A

(//input[1])[2]

C

(//input[1])[ last()]]

C

//input[2]

BD

(//input[2])[1]

B

(//input[2])[2]

D

(//input[2])[ last()]]

D

(//input)[position()=1]

A

(//input)[position()=2]

B

(//input)[position()>=3]

CD

(//input)[position()=1 OR position()=last()]

AD

 

Note: In the above table, we mentioned all the matching elements, a single xpath expression may match multiple elements, but puppeteer will always return first matching element.

You can write the script and test these using our Test Page

group-index-in-xpath-0
 

All Chapters
Author