如何减少appium中的元素搜索默认时间

How to reduce element searching default time in appium

我刚刚注意到,当元素不存在时,Appium 和 Selenium 至少需要 2 分钟才能找到元素。

我想缩短搜索时间。

代码是:

 if(!driver.findElements(By.id(AppConstants.notificationcount)).isEmpty())
{

  // DO SOMETHING

}
else
{

   System.out.println("No Element available");    
}

现在大部分时间我的元素不可用,所以我希望 appium 检查它并快速重定向到 ELSE 部分,但它需要很长时间,有什么解决方案吗?

更快的检查方法是将元素存储在列表中,然后检查它是否为空

List<WebElement> elements = driver.findElements(By.id("AppConstants.notificationcount"));
 if (elements.isEmpty()) {
    System.out.println("No Element available");
        }else{
          elements.get(0).click();//if present click the element
}

希望对您有所帮助。

你检查过你的隐式等待时间了吗?
默认情况下为 0,但也许您将其设置为大于 2 分钟的值:

driver.manage().timeouts().implicitlyWait(timeInSeconds, TimeUnit.SECONDS);

如果您的隐式等待时间大于 0,并且您正在搜索具有

的元素
driver.findElements(...);

但是你的元素不存在,然后Selenium 将等待整个指定的时间!


Selenium 仅不等待,当至少找到一个元素时。在这种情况下,它将搜索页面一次,然后 return 立即使用找到的元素列表。

所以 findElements() 非常适合检查元素是否存在,但 仅当您指定非常短的隐式等待时间时检查不存在 (或默认 0).


如果您出于任何原因绝对需要隐式等待时间 > 0,那么您可以创建自己的方法来处理此问题,如 this solution.


在您的情况下,您可以在发布代码之前将隐式等待时间设置为 0:

driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
// then follows your code:
if(!driver.findElements(By.id(AppConstants.notificationcount)).isEmpty())
{

  // DO SOMETHING

}
else
{

   System.out.println("No Element available");    
}

如果您在其他地方需要隐式等待时间而不是 0,那么只需在您的代码段后将其设置回原始值即可。