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

查看:109
本文介绍了如果元素不存在,则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. 将hiddeny_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.

在操作完成后隐式设置为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天全站免登陆