【问题标题】:Can isDisplayed() return false without breaking run in Selenium?isDisplayed() 可以在不中断 Selenium 运行的情况下返回 false 吗?
【发布时间】:2017-04-04 09:31:53
【问题描述】:

我想通过 .isDisplayed() 方法使用条件函数。只要此方法返回 true,一切正常。

我认为这里不需要HTML,因为我在页面上只有一个按钮可见,这是正确找到的(我成功点击了带有以下xpath的按钮。

现在我尝试:

if (driver.findElement(By.xpath("//a[@id='button1']")).isDisplayed()) {
     //do stuff
}
else {
    //do other stuff
}

甚至

WebElement withdrawnBtn = driver.findElement(By.xpath("//a[@id='button1']"));
boolean isVisible = withdrawnBtn.isDisplayed();
if (isVisible) {
     //do stuff
}
else {
    //do other stuff
}

但是两个条件都失败了,如果在第一次运行中应该执行来自else的代码,因为每次按钮不可用时,都会有失败指向driver.findElement(By.xpath("//a[@id='button1']")).isDisplayed());-失败,因为按钮是不显示。当按钮不显示而不是代码失败时,我需要做点什么......

【问题讨论】:

  • 查看 HTML 标准。 DOM 中的任何元素都可以(如果我要简化的话):显示(通常是最明显和最常见的类型)、缺失(任何地方都没有这样的元素)、隐藏(通过多种方法,包括设置visibility:none)。您将不得不重新考虑您的代码,通常快速答案是不正确的。

标签: java selenium selenium-webdriver


【解决方案1】:

在检查isDisplayed条件之前,我们需要检查页面上是否存在元素,否则会抛出Nosuchelementfound异常

driver.findElements("Locator").size()--如果页面上存在该元素,将返回整数值。

以下是修复代码。

  int size = driver.findElements("Locator").size();
    if(size!=0){
         if(driver.findElement("Locator").isDisplayed()){
             // do operations
         }
    }

读完 cmets 后,我知道 isEmpty 是更好的使用方式,而不是 size 我对上面的代码进行了更改。

WebDriver driver;
List<WebElement> webElements = driver.findElements(By.xpath("test"));
if(!webElements.isEmpty()){
    if(driver.findElement(By.xpath("test")).isDisplayed()){
        // do operations
    }
 }

试试看,如果它适合你,请告诉我

【讨论】:

  • 如果您唯一感兴趣的是Collection::isEmpty(),则应避免使用Collection::size()。某些类型的集合需要花费很长时间来计算它们的大小,通常不仅仅是说它们是否为空。
  • isEmpty 看起来更好 - int 与 boolean 相比占用更多空间:)
  • 谢谢@M。 Prokhorov,我相应地更新了我的代码。
【解决方案2】:

您还可以使用以下方法来识别元素是否存在:

private boolean isPresent(WebElement element) {
try {
    element;
} catch (NoSuchElementException e) {
    return false;
}
return true;
}

【讨论】:

    【解决方案3】:

    好的,我正在考虑捕获 NoElementFound 异常,但我发现了这个问题: Selenium Webdriver: best practice to handle a NoSuchElementException

    使用上面我使用的链接:

    List<WebElement> withdrawnBtn = driver.findElements(By.xpath("//a[@id='button1']"));
    if (withdrawnBtn.size() != 0) {
         //do stuff
    }
    else {
        //do other stuff
    }
    

    【讨论】:

    • Michal 我的第一个解决方案也是一样的。
    【解决方案4】:

    您可以使用 isEmpty() 方法代替 size() 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 2017-05-07
      相关资源
      最近更新 更多