【问题标题】:findElement method showing an exception显示异常的 findElement 方法
【发布时间】:2020-04-04 16:57:43
【问题描述】:

我需要单击一个按钮,该按钮可能以 50% 的几率出现​​,决定使用 try/catchfindElementBy。然而try/catch 不起作用,我遇到了一个例外。也许有更有效的方法来处理该按钮?

driver.manage().timeouts().implicitlyWait(5000, TimeUnit.MILLISECONDS);
WebDriverWait wait = new WebDriverWait(driver,5);
try {
    WebElement element = driver.findElement(By.xpath("buttonXpath"));
    element.click();
}
catch (NoSuchElementException e){ }

【问题讨论】:

  • 你能显示异常堆栈跟踪吗?请同时添加您的导入,尤其是 NoSuchElementException 之一。
  • 您遇到的异常是什么? NoSuchElementException?

标签: java selenium try-catch nosuchelementexception


【解决方案1】:

您可能会看到 NoSuchElementException,这可能由于多种原因而发生。详细讨论可以在NoSuchElementException, Selenium unable to locate element


解决方案

最好的方法是构造一个Locator Strategy,它在HTML DOM 中唯一标识所需元素,如下讨论:

现在根据最佳实践,在调用click() 时,总是在try-catch{} 块中为elementToBeClickable() 引入WebDriverWait,如下所示:

try{
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("buttonXpath"))).click();
    System.out.println("Element was clicked")
}
catch (TimeoutException e){ 
    System.out.println("Element wasn't clicked") 
}

【讨论】:

  • OP 从未说过他得到的异常是NoSuchElementException
  • @Guy 好吧,你可以看到 OP 在他的代码试验中尝试处理 NoSuchElementException
  • 是的,他说尽管try catch,他仍然有一个例外。除非他使用了错误的导入,否则他还有另一个例外。但是如果没有更多细节,你无法知道它是哪一个。
  • 没有TimeoutException你想达到什么目的?
【解决方案2】:

这对你有用:

List<Webelement> element = driver.findElements(By.xpath("buttonXpath"));

if(element.size() > 0) {
    element.get(0).click();
}

【讨论】:

    【解决方案3】:

    使用方法检查此元素是否在您的屏幕上:

    if (!driver.findElementsByXPath("buttonXpath`enter code here`").isEmpty()) {
       driver.findElementByXPath("buttonXpath`enter code here`").click();
    }
    

    【讨论】:

    • 您正在执行两次 Xpath 查询。存储元素列表并访问它的第一个元素,当它不为空时。
    • 您可以随意使用此列表做任何您想做的事情。我的例子只是展示了避免异常的方法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多