Reputation: 461
I'm trying to click the last span element in the following HTML
<div class="rating rating-set js-ratingCalcSet" >
<div class="rating-stars js-writeReviewStars">
<span class="js-ratingIcon glyphicon glyphicon-star fh"></span>
<span class="js-ratingIcon glyphicon glyphicon-star lh"></span>
...
<span class="js-ratingIcon glyphicon glyphicon-star fh"></span>
<span class="js-ratingIcon glyphicon glyphicon-star lh"></span>
</div>
</div>
using Selenium in Java, with the following code:
driver.findElement(By.xpath("(//div[contains(@class, 'js-writeReviewStars')]//span)[last()]")).click();
This returns an exception:
org.openqa.selenium.InvalidSelectorException: invalid selector: Unable to locate an element with the xpath expression (//div[contains(@class, 'js-writeReviewStars')]//span)[last()] because of the following error:
SyntaxError: Unexpected token }
...
*** Element info: {Using=xpath, value=(//div[contains(@class, 'js-writeReviewStars')]//span)[last()]}
I have checked the validity of the xpath expression and it seems correct (using https://www.freeformatter.com/xpath-tester.html), as it finds the target element.
I have tried surrounding the whole expression in parentheses, which did not work.
Upvotes: 2
Views: 671
Reputation: 193088
You were pretty close. To identify the last()
<span>
tag within the <div>
tag you need to remove the extra pair of (
and )
from the xpath.
So effectively you need to change:
driver.findElement(By.xpath("(//div[contains(@class, 'js-writeReviewStars')]//span)[last()]")).click();
As:
driver.findElement(By.xpath("//div[contains(@class, 'js-writeReviewStars')]//span[last()]")).click();
Upvotes: 2