selenium各类等待处理方法

来源:互联网 发布:mac 测量图片尺寸工具 编辑:程序博客网 时间:2024/05/16 17:03
1)隐式等待,设置针对全局的等待时间,webdriver中执行所有命令 的超时时间都设置为30秒了
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
说明:如findElement方法,找不到元素会默认等待三十秒。
改进方法:
private boolean isElementPresent(By by) {
    try {
      driver.manage().timeouts().implicitlyWait(1, TimeUnit.SECONDS);
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }
2)显示的等待
说明:如果只是仅仅想判断页面是不是加载到某个地方了,就可以用第一种方法; 但如果需要得到某个WebElement,两种方式都可以,只是第一种方式还需要再多一步获取的操作.
方式一:
boolean wait = new WebDriverWait(driver, 15).until(
ExpectedConditions.presenceOfElementLocated(By.cssSelector("css locator"))
); // 判断并等待某个元素在页面中存在
说明:15是要等待的秒数.如果没有满足until()方法中的条件,就会始终在这里wait 15秒,依然找不到,就抛出异常.
①presenceOfElementLocated:是否存在
②visibilityOfElementLocated:是否可见,存在的东西不一定可见
方式二:
WebDriver driver = new FirefoxDriver();
driver.get( www.baidu.com);
WebElement e = (new WebDriverWait( driver, 10)) .until(
new ExpectedCondition< WebElement>(){
@Override
public WebElement apply( WebDriver d) {
return d.findElement( By.id("id locator"));
}
}
);
说明:这样就通过回调函数,直接获得了这个WebElement.也就是页面元素.
3)线程休眠
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
原创粉丝点击