Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xpath how to get before the last element of <a>

I have this html

<a class=pagination_klass></a>
<a class=pagination_klass></a>
<a class=pagination_klass></a>
<a class=pagination_klass></a>
<a class=pagination_klass>HERE</a>
<a class=pagination_klass></a>

I want to get the before last <a>

I tried this:

.//a[@class='pagination_klass' and position() = (last()-1)]/@href

but I got empty results.

help please.

note

I need to compare on the class name too

like image 269
user2226785 Avatar asked Apr 07 '14 17:04

user2226785


People also ask

How do you select the last element in XPath?

Using XPath- last() method, we can write the Java code along with the dynamic XPath location as: findElement(By. xpath("(//input[@type='text'])[last()]"))

Which of the following options can create a XPath to get the second last element from the unordered list?

You can use the last() feature of xpath.

How use contains XPath?

The syntax for locating elements through XPath- Using contains() method can be written as: //<HTML tag>[contains(@attribute_name,'attribute_value')]


2 Answers

Hi you got it almost correct. I removed . selector (current node selector) at beginning of XPath and I test it here on Xpath tester. It works fine for me.

//a[@class='pagination_klass' and position() = (last()-1)]/@href

For

<html>
...
<a class='pagination_klass'></a>
<a class='pagination_klass'></a>
<a class='pagination_klass'></a>
<a class='pagination_klass'></a>
<a class='pagination_klass' href='LINK'>HERE</a>
<a class='pagination_klass'></a>
..
</html>

will be result attribute node href='LINK'.

like image 185
Jaroslav Kubacek Avatar answered Sep 18 '22 14:09

Jaroslav Kubacek


Your expression

.//a[@class='pagination_klass' and position() = (last()-1)]/@href

will select the second-to-last of all links but only if its class equals pagination_klass. If you want to find the second-to-last of all pagination_klass links, try:

.//a[@class='pagination_klass'][last()-1]/@href
like image 42
nwellnhof Avatar answered Sep 20 '22 14:09

nwellnhof