XPath 1 provides a powerful function named “position()” . Before we move further, let’s get in to a scenario where we need this.
Consider below web page. We have six different tab headers which are actually country capital names. I used W3School reference to get below html design.
If I ask you to give me Xpath for Nth indexed tab header i.e. 2nd Header or 4th header. Probably you will write XPath as below :-
(//button[@class=’tablink’])[2] – For 2nd indexed
(//button[@class=’tablink’])[4] – For 4th indexed
Note:- In XPath index starts from one (1) not from zero as we see in programming languages.
Now if I ask you to:-
- Give me a XPath which locates tab headers from 2nd to 4th index?
- Give me a XPath which locates 2nd and 4th indexed tab headers together?
- Give me a XPath which locates tab headers which are before 5th index?
- Give me a XPath which locates tab header which are after 2nd index?
Now here you need to use XPath function called “function()”.
The position
function returns a number equal to the context position from the expression evaluation context.
We can replace index with position as below:-
(//button[@class=’tablink’])[2] -> //button[@class=’tablink’][position()=2]
(//button[@class=’tablink’])[4] -> //button[@class=’tablink’][position()=4]
We can use conditional operator like greater than , less than , greater than and equal to, less than and equal to and not equal to etc. Even we can use logical operator like AND & OR with it.
To get all headers from 3rd index onward i.e 4th, 5th and 6th
//button[@class=’tablink’][position()>3]
To get all headers from 3rd index including i.e 3rd, 4th, 5th and 6th
//button[@class=’tablink’][position()>=3]
To get all headers before 5th index i.e 1st, 2nd, 3rd and 4th
//button[@class=’tablink’][position()<5]
To get all headers before 5th index including i.e 1st, 2nd, 3rd ,4th and 5th
//button[@class=’tablink’][position()<=5]
To get all headers between 2nd and 5th index i.e 3rd and 4th
//button[@class=’tablink’][position() >= 3 and position() <= 4]
To get only 2nd and 4th indexed locators
//button[@class=’tablink’][position() = 3 or position() = 4]
To get all headers except 3rd index
//button[@class=’tablink’][position() != 3]
To get all headers except 3rd and 2nd index
//button[@class=’tablink’][position() != 3 and position() !=2]
Click on the buttons inside the tabbed menu:
London
London is the capital city of England.
Paris
Paris is the capital of France.
Tokyo
Tokyo is the capital of Japan.
Oslo
Oslo is the capital of Norway.
New Delhi
New Delhi is the capital of India.
Canberra
Canberra is the capital of Australia.
You can clone code from my git repo.
If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning
Find all Selenium related post here, all API manual and automation related posts here and find frequently asked Java Programs here.
Many other topics you can navigate through menu.