org.openqa.selenium.InvalidSelectorException: invalid selector SyntaxError: Unexpected token } using XPath through Selenium Java

org.openqa.selenium.InvalidSelectorException: invalid selector SyntaxError: Unexpected token } using XPath through Selenium Java

我正在尝试单击下面的最后一个 span 元素 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>

在 Java 中使用 Selenium,代码如下:

driver.findElement(By.xpath("(//div[contains(@class, 'js-writeReviewStars')]//span)[last()]")).click(); 

这returns一个例外:

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()]}

我检查了 xpath 表达式的有效性,它似乎是正确的(使用 https://www.freeformatter.com/xpath-tester.html),因为它找到了目标元素。

我试过用括号括起整个表达式,但没有用。

你们非常接近。要识别 <div> 标签中的 last() <span> 标签,您需要删除额外的 () 来自 .

如此有效你需要改变:

driver.findElement(By.xpath("(//div[contains(@class, 'js-writeReviewStars')]//span)[last()]")).click(); 

作为:

driver.findElement(By.xpath("//div[contains(@class, 'js-writeReviewStars')]//span[last()]")).click();