java - 使用 ExpectedConditions 类断言元素不存在

标签 java selenium selenium-webdriver

我正在尝试使用 ExpectedConditions 类来执行与 Selenium 相关的断言,但我无法找到断言给定元素不存在的事实上的最佳实践。我正在尝试使用这样的东西......

Assert.assertFalse(ExpectedConditions.presenceOfElementLocated(By.xpath(myXpath)).apply(driver1));

但这当然不会编译,因为 presenceOfElementLocated 返回 WebElement 而不是 boolean 值,这让我很沮丧。你推荐什么作为实现我想要的最佳实践?

编辑: 已接受的问题答案已转换为 Java ...

public static boolean elementXpathPresent(WebDriver driver,String elementXpath) {
    try {
        WebDriverWait wait = new WebDriverWait(driver,10);
        wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(elementXpath)));
    } catch (TimeoutException e) {
        return false;
    }   
    return true;
}

最佳答案

好吧,如果不存在匹配选择器的 element,使用 ExpectedConditions 最终将抛出 NoSuchElementException。在这种情况下,您可能希望将 try catch 与 ExpectedConditions 一起使用,或者简单地使用 findElements()size() 来查看它是否找到任何元素根本。看我的回答here

这是您的另一种选择。用 C# 编写,但转换起来相当容易

/// <summary>
/// 
/// </summary>
/// <returns></returns>
public bool Test()
{
    try
    {
        new WebDriverWait(Driver, TimeSpan.FromSeconds(10)).Until(
            ExpectedConditions.ElementExists(By.XPath("MyXpath")));
    }
    catch (NoSuchElementException)
    {
        return false;
    }

    return true;

}

/// <summary>
/// 
/// </summary>
public void Assertion()
{
    Assert.IsTrue(Test());
}

关于java - 使用 ExpectedConditions 类断言元素不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28504546/

相关文章:

java - 如何比较Kafka中的流记录

java - Websphere 上 dom4j 的空指针异常

java - 一个测试类中存在的 @BeforeMethod 是否可以应用于另一个测试类中的方法?

java - 如何一一运行两个java文件-Eclipse?

vba - Selenium VBA 代码在浏览器中粘贴数据

java - Android - 使用简单日期格式的字符串到时间(仅)

java - 为什么我的 GUI Java 程序中的输出文件为空?

python - 在 python 中初始化 MSEdge 浏览器,得到 TypeError : Level not an integer or a valid string: None

java - 如何在selenium中显式等待元素中的文本被更改

python - 使用 PhantomJS 进行代理身份验证