Java 硒:寻找元素“;旁边是;其他元素
我正在使用Selenium将web测试添加到我的项目中。我已经进行了一系列测试,使用以下方法检查特定元素:Java 硒:寻找元素“;旁边是;其他元素,java,testing,selenium,Java,Testing,Selenium,我正在使用Selenium将web测试添加到我的项目中。我已经进行了一系列测试,使用以下方法检查特定元素: final WebElement dateElement = web.findElement(By.id(elementId)); 这个很好用。 现在我有另一个要求。这在我生成的页面中: <input type="text" id="dateElement" name="dateElement" value="bunch of monkeys" tabindex="101" pla
final WebElement dateElement = web.findElement(By.id(elementId));
这个很好用。
现在我有另一个要求。这在我生成的页面中:
<input type="text" id="dateElement" name="dateElement" value="bunch of monkeys" tabindex="101" placeholder="yyyy-mm-dd">
<span class="error">dateElement is an invalid date</span>
dateElement是无效的日期
我如何获得错误消息?
我想要一个允许我请求带有类“error”的span元素的东西,该类正好位于dateElement之后
(这个错误消息是由SpringMVC生成的,所以直接更改它并不容易。我想可能吧,但我不希望如此)
欢迎任何其他想法。好的,我已经找到了一个使用Xpath和以下兄弟的解决方案,它并不太复杂
final WebElement errorElement = web.findElement(By.xpath("//*[@id='" + elementId + "']/following-sibling::span[@class='error']"));
这给了我我想要的,当它不在这里时抛出一个
NoSuchElementException
,这正是我想要的。太好了,我还需要答案。这甚至可以使用final WebElement errorElement=dateElement.findElement(By.xpath(“following sibling::span[@class='error'])简化代码>如果您有实际的WebElement日期元素
可用。您必须使用该元素作为搜索的根,但请注意,在这种情况下,xpath表达式不应以/
(或/
)开头,否则它将从文档根进行搜索。谢谢neXus,这正是我要寻找的方法!为什么不用errorElement
代替dateElement
?如果这是一个与dateElement无关的错误呢?@tishma,因为这就是我们要使用的
elementSelector = "input + span[class='error']";
final WebElement dateElement = web.findElement(By.cssSelector(elementSelector));