使用WebDriverWait类处理等待(sleep)的问题
2016-03-04 16:52
603 查看
用selenium进行web UI的自动化开发时,经常遇到loading需要等待的时候,或者需要验证一个action之后某个dialog是否呈现或者消失。对于这类情况是不建议用sleep(xx)来死等,因为你无法准确判断要等多久,少了就会报error,多了就会浪费整个脚本跑的时间。聪明的做法就是灵活等待,WebDriverWait(org.openqa.selenium.support.ui)这个类是很好的选择。
/** * Wait until the element visible with customized timeout * @param driver * @param locator * @param errorMessage * @return */ public WebElement waitForElementVisible(WebDriver driver,final By locator, long timeOutInSeconds, String errorMessage) { Function<WebDriver, WebElement> waitFn = new Function<WebDriver, WebElement>() { @Override public WebElement apply(WebDriver driver) { try { WebElement el = driver.findElement(locator); if (el.isDisplayed()) { return el; } } catch (Exception e) { } return null; } }; WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds); if (errorMessage != "") { wait.withMessage(errorMessage); } else { wait.withMessage("Cannot find Element: " + locator.toString()); } return wait.until(waitFn); }
/** * Wait until the element present with customized timeout * @param driver * @param locator * @param errorMessage * @return */ public Boolean waitForElementPresent(WebDriver driver,final By locator, long timeOutInSeconds, String errorMessage) { Function<WebDriver, Boolean> waitFn = new Function<WebDriver, Boolean>() { @Override public Boolean apply(WebDriver driver) { try { driver.findElement(locator); return true; } catch (Exception e) { return false; } } }; WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds); if (errorMessage != "") { wait.withMessage(errorMessage); } else { wait.withMessage("Cannot find Element: " + locator.toString()); } return wait.until(waitFn); }
相关文章推荐
- HDOJ-1789 Doing Homework again
- 使用AFN 的POST请求出现错误"Error Domain=NSCocoaErrorDomain Code=3840 "决绝方案
- HDU 3356 ||POJ 3996Air Strike(贪心)
- hdu 4630 No Pain No Game 线段树离线处理
- pthread_cond_wait()与pthread_cond_signal()
- quartz报错:SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-op
- Forcing the Removal of a Domain Controller
- Thread 常搞混的几个概念sleep、wait、yield、interrupt
- 打造你的办公环境-email篇
- 【什么是长尾关键词(Long Tail Keyword)】
- 在mac上用Xcode写程序, run的时候总是失败, 显示clang: error: linker command failed with exit code 1
- How To Reclaim Wasted Space on The Segment (Table, Index and LOB) and Tablespace Levels (文档 ID 16827
- 怎样用好ZBrush中的PaintStop插件
- At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for 。。。
- hair gene (news)
- 软件RAID5项目实战!!!
- 软件RAID5项目实战!!!
- Raid 5 故障恢复
- 1086 Tree Traversals Again
- UVALive 6900 Road Repair [树分治+线段树]