There may be cases where XPath Statements cant locate the elements by using element tags and its attributes as there are other elements with similar tags or attributes. In those cases we have to find the first unique element from its siblings and add the index value to it.
Adding Index value to the XPath Statement will be explained in the below steps:
1. Open http://compendiumdev.co.uk/selenium/basic_html_form.html in Firefox Browser
2. Select the Firepath tab from the FireBug Options as shown below:
3. Now type the XPath Statement //tr into the XPath field as shown below and click on 'Eval' button
4. Observe that more than one table rows are located on the page as show below:
5. But we want to high light only one row i.e. 'TextArea Comment' row instead of locating all the rows. In order to distinguish our row from remaining all the rows, we've to first find if there are any unique attributes in our row by viewing the html code of our row as shown below:
6. From the above screenshot its very clear that there are no attributes to distinguish our row from other sibling rows. In this kind of situations we've to add index value to the XPath statement to distinguish our row with other rows. To start with lets add index 1 to the XPath and enter the resultant XPath //tr into the XPath field as shown below and click on 'Eval' button:
7. Ensure that the first row element got high lighted on the page as shown below:
8. Now lets high light the third row i.e. our required 'TextArea Comment' Row by adding the index value as 3 to the XPath Statement. So lets enter the XPath Statement //tr into the XPath field as shown below and click on 'Eval' button:
9. Observe that the 'TextArea Comment' row is now high lighted on the page as shown below:
To conclude, if the element to be located doesn't have any attributes to distinguish it from the other similar sibling elements, then we've to add index value to the XPath statement to make the element distinguished from others and identified correctly.
Please comment below to feedback or ask questions.
XPath Optimization Strategy Four - Use Relative XPath Statements instead of Absolute XPath Statements will be explained in the next post.