如果元素不存在,isElementPresent 会非常慢. [英] isElementPresent is very slow in case if element does not exist.

查看:28
本文介绍了如果元素不存在,isElementPresent 会非常慢.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下面的代码来检查我网页上的元素

I am using below code to check for element on my web page

private boolean isElementPresent(By by) {
try {       
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
        return false;
    }
    catch (Exception e)
    {       
        return false;
    }

  }

如果结果中出现特定区域,我需要检查我的程序

I need to check in my program if a particular region appears in result as below

isElementPresent(By.xpath(".//*[@id='header']")));

如果存在此功能,则此功能会快速完成,但如果不存在上述功能,则它会运行很长时间.

If this is present this function completes quickly but if above is not present then it run for very long.

有人可以帮我解决这个问题,以便可以快速执行此检查吗?

Could some one please help me in resolving this issue so that this check can be performed quickly?

推荐答案

这里你缺少一些东西,这就是为什么它正在等待如果没有元素.findElement 将等待一个元素隐式指定的时间.因此需要在该方法中将该时间设置为零.

Here you are missing somethings that is why it is waiting If there is not element. findElement will wait for an element implicitly specified time. so need to set that time to zero in that method.

isElementPresent(WebDriver driver, By by) {  
    driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);  
    try {  
        driver.findElement(by);  
        return true;  
    } catch (NoSuchElementException e) {  
        return false;  
    } finally {  
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);  
    }  
}

这里有 4 件重要的事情.按顺序:

There are 4 important things going on here. In order:

  1. 将implicity_wait 设置为0,以便WebDriver 不会隐式等待.

  1. Setting implicity_wait to 0 so that WebDriver does not implicitly wait.

找到元素时返回 True.

Returning True when the element is found.

捕获 NoSuchElementException 并在我们发现元素不存在时返回 False,而不是通过异常停止测试.

Catching the NoSuchElementException and returning False when we discover that the element is not present instead of stopping the test with an exception.

在操作完成后将implicitly_wait设置回30,以便WebDriver将来隐式等待.

Setting implicitly_wait back to 30 after the action is complete so that WebDriver will implicitly wait in future.

这篇关于如果元素不存在,isElementPresent 会非常慢.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆