Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore first element in xpath

Tags:

xpath

How can I ignore first element and get rest of the elements?

<ul>   <li><a href="#">some link</a></li>   <li><a href="#">some link 2</a></li>   <li><a href="#">link i want to find</a></li> </ul> 

Thanks

like image 488
priyank Avatar asked Apr 14 '10 00:04

priyank


People also ask

How to exclude first element in XPath?

You need to wrap the expression that selects the a in parenthesis to group them in a node-set, then apply the predicate filter on position. That will find all a elements except the first one (since there is no a preceding the first one).

How do I select the second element in XPath?

//div[@class='content'][2] means: Select all elements called div from anywhere in the document, but only the ones that have a class attribute whose value is equal to "content". Of those selected nodes, only keep those which are the second div[@class = 'content'] element of their parent.

How do I select the first child in XPath?

The key part of this XPath is *[1] , which will select the node value of the first child of Department .

What is text () in XPath?

XPath text() function is a built-in function of the Selenium web driver that locates items based on their text. It aids in the identification of certain text elements as well as the location of those components within a set of text nodes. The elements that need to be found should be in string format.


2 Answers

if you want to ignore the "first" element only then:

//li[position()>1] or (//a)[position()>1]  

if you want the last only (like your example seems to suggest):

//li[last()] or (//a)[last()] 
like image 157
t00ny Avatar answered Oct 02 '22 21:10

t00ny


You can use position() to skip over the "first" one, but depending on which element you are interested in and what the context is, you may need a slight variation on your XPATH.

For instance, if you wanted to address all of the li elements and get all except the first, you could use:

//li[position()>1] 

and it would work as expected, returning all of the li elements except for the first.

However, if you wanted to address all of the a elements you need to modify the XPATH slightly. In the context of the expression //a[position()>1] each one of the a elements will have a position() of 1 and last() will evaluate to true. So, it would always return every a and would not skip over the first one.

You need to wrap the expression that selects the a in parenthesis to group them in a node-set, then apply the predicate filter on position.

(//a)[position()>1]

Alternatively, you could also use an expression like this:

//a[preceding::a] 

That will find all a elements except the first one (since there is no a preceding the first one).

like image 22
Mads Hansen Avatar answered Oct 02 '22 21:10

Mads Hansen