Reputation: 1071
I'm using Selenium to automate some web tests and need to select elements by xpath.
<ul class="class1">
<div>
...
<span class="spanClass"> Text </span>
...
</div>
</ul>
<div class="class2">
<div>
...
<span class="spanClass"> Text </span>
...
</div>
</div>
If I use an xpath like:
(//ul[@class='class1']//span)[last()]
This selects the last span element from the div class2. But I need the last span element from the ul class1.
From what I understand I need to use ".//span" instead of "//span" so I tried:
(//ul[@class='class1'].//span)[last()]
But this is not a valid expression. However if I do:
(//ul.//span)[last()]
This is now a valid expression, but don't guarantee that I use the correct ul element as node (it also seems to be otherwise incorrect for what I want anyway). So this won't work.
I want to select only the last span element from the ul class1. There will be an unkown number of identical span elements for both the ul class1 and in the div class2. So I can't select the Nth span element as I won't know the number.
Upvotes: 0
Views: 1851
Reputation: 89285
(//ul[@class='class1']//span)[last()]
should've done what you wanted. The expression means, find all span
within ul[@class='class1']
, and return only the last. See a demo here. Given input HTML like the following :
<root>
<ul class="class1">
<div>
...
<span class="spanClass"> Text 1</span>
...
</div>
</ul>
<div class="class2">
<div>
...
<span class="spanClass"> Text 2</span>
...
</div>
</div>
</root>
..the output is <span class="spanClass"> Text 1</span>
, as wanted.
The last expression (//ul.//span)[last()]
, while valid, it doesn't do what you think it does. It will try to find all <span>
within <ul.>
(notice the dot) element and then returning only the last found <span>
.
Upvotes: 1