首页 > 解决方案 > org.openqa.selenium.InvalidSelectorException: 无效选择器 SyntaxError: Unexpected token } 通过 Selenium Java 使用 XPath

问题描述

我正在尝试单击以下 HTML 中的最后一个 span 元素

<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(); 

这会返回一个异常:

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),因为它找到了目标元素。

我尝试将整个表达式括在括号中,但没有成功。

标签: javaseleniumselenium-webdriverxpathxpath-1.0

解决方案


你非常接近。要识别last() <span>标签中的<div>标签,您需要从(中删除额外的和对。)

如此有效地你需要改变:

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

作为:

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

推荐阅读