2

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.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
fugasjunior
  • 461
  • 1
  • 6
  • 22

1 Answers1

2

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 .

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(); 
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352