【问题标题】:Selenium: find element "next to" other elementSelenium:在其他元素“旁边”找到元素
【发布时间】:2011-12-21 22:56:47
【问题描述】:

我正在使用 Selenium 将 Web 测试添加到我的项目中。我已经有一堆测试使用以下方法检查特定元素:

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 之后请求具有类“错误”的 span 元素的东西。

(此错误消息是由 Spring MVC 生成的,因此直接更改它并不容易。我猜可能,但我不想)。

欢迎任何替代想法。

【问题讨论】:

    标签: java testing selenium


    【解决方案1】:

    好的,我已经找到了使用 Xpath 和 follow-sibling 的解决方案,它并不太复杂。

    final WebElement errorElement = web.findElement(By.xpath("//*[@id='" + elementId + "']/following-sibling::span[@class='error']"));
    

    这给了我我想要的,当它不在这里时抛出一个NoSuchElementException,这正是我想要的。

    【讨论】:

    • 太好了,我也需要答案
    • 如果你有实际的WebElement dateElement 可用,甚至可以使用final WebElement errorElement = dateElement.findElement(By.xpath("following-sibling::span[@class='error']")); 来简化。您必须将该元素用作搜索的根,但请注意,在这种情况下,xpath 表达式不应以 //(或 /)开头,否则它将从文档根开始搜索。
    • 感谢 neXus,这正是我正在寻找的方法!
    【解决方案2】:
    elementSelector = "input + span[class='error']";
    
    final WebElement dateElement = web.findElement(By.cssSelector(elementSelector));
    

    【讨论】:

    • 为什么不用errorElement 而不是dateElement?如果是与 dateElement 无关的错误怎么办?
    • @tishma 因为那是 OP 使用的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 2022-06-12
    • 2021-09-05
    • 1970-01-01
    • 2011-10-18
    • 2019-04-22
    相关资源
    最近更新 更多