java - 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),因为它找到了目标元素。
我尝试将整个表达式括在括号中,但没有成功。
解决方案
你非常接近。要识别last()
<span>
标签中的<div>
标签,您需要从xpath(
中删除额外的和对。)
如此有效地你需要改变:
driver.findElement(By.xpath("(//div[contains(@class, 'js-writeReviewStars')]//span)[last()]")).click();
作为:
driver.findElement(By.xpath("//div[contains(@class, 'js-writeReviewStars')]//span[last()]")).click();
推荐阅读
- r - Adding a True or False column for a dataframe if it matches a column of a different dataframe in R?
- visual-studio-code - Remote SSH on VS Code in WSL2 password prompt
- python - Problems with my Discord Bot's Leveling system and role giver
- javascript - Is it possible to make "keydown" events trigger existing click events in javascript?
- database - Can't post (create) 3rd level nested model in ASP.NET Core 3.1 MVC
- gephi - How to see all the reachable nodes from a selected node in a directed graph in Gephi
- javascript - Flatten an array of unknown deep objects, with named properties, in Async/Await JavaScript (or better TypeScript)
- c# - .NET 5 使用 Windows Shell 的方式是什么?
- java - Is it possible to modify a compareTo() method so as to ensure that Insertion sort and Selection sort return the same output no matter what?
- react-native - Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'camera.takePictureAsync') React-Native expo-camera