【问题标题】:org.openqa.selenium.InvalidSelectorException: invalid selector SyntaxError: Unexpected token } using XPath through Selenium Javaorg.openqa.selenium.InvalidSelectorException: 无效选择器 SyntaxError: Unexpected token } 通过 Selenium Java 使用 XPath
【发布时间】:2019-08-30 11:57:43
【问题描述】:

我正在尝试单击以下 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),因为它找到了目标元素。

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

【问题讨论】:

    标签: java selenium selenium-webdriver xpath xpath-1.0


    【解决方案1】:

    你已经很接近了。要在&lt;div&gt; 标记中识别last() &lt;span&gt; 标记,您需要从 中删除额外的一对 () .

    如此有效地你需要改变:

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

    作为:

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

    【讨论】:

    • 我认为你在 xpath 的开头还有额外的(
    猜你喜欢
    • 2021-11-15
    • 2020-05-22
    • 2018-09-29
    • 2012-01-31
    • 2013-10-13
    • 2016-03-27
    • 2012-05-17
    • 2019-02-10
    • 2019-11-10
    相关资源
    最近更新 更多