没有这样的元素:无法找到元素:当我使用elementToBeClickable方法时

时间:2019-06-12 09:47:14

标签: java selenium selenium-webdriver

我必须等待某个元素出现,然后单击它。这是我尝试并获得NoSuchElementException的代码。

我有300秒等待元素,但是它正在尝试查找元素: tpo.fwOptimizationTestResults()无需等待300秒

WebElement fwResults = (new WebDriverWait(driver, 300))
        .until(ExpectedConditions.elementToBeClickable(tpo.fwOptimizationTestResults())); 

public WebElement fwOptimizationTestResults() {
    //return driver.findElement(By.xpath("//*[@class='table table-condensed table-bordered']"));
    return driver.findElement(By.xpath("//table[contains(@class, 'table-condensed')]"));
}

错误:

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//table[contains(@class, 'table-condensed')]"}
  (Session info: chrome=75.0.3770.80)

2 个答案:

答案 0 :(得分:2)

异常不是来自elementToBeClickable,而是来自fwOptimizationTestResults。您正在使用driver.findElement()引发异常并在预期条件之前进行评估。

有两个重载elementToBeClickable(WebElement)elementToBeClickable(By),您应该使用第二个重载

WebElement fwResults = (new WebDriverWait(driver, 300)).until(ExpectedConditions.elementToBeClickable(By.xpath("//table[contains(@class, 'table-condensed')]")));

答案 1 :(得分:1)

您可能需要修改代码,以将ignoring节添加到WebDriverWait  因此它不会在NPEs上失败:

WebElement fwResults = (new WebDriverWait(driver, 5))
        .ignoring(NullPointerException.class)
        .until(ExpectedConditions.elementToBeClickable(tpo.fwOptimizationTestResults()));

然后将您的WebElement函数放在try block内,而不是引发异常-如果找不到元素,请返回null

public WebElement fwOptimizationTestResults() {
    try {
        return driver.findElement(By.xpath("//table[contains(@class, 'table-condensed')]"));
    } catch (NoSuchElementException ex) {
        return null;
    }
}

更多信息: