平平庸庸

重载 findElement() 以添加等待时间

上一篇 / 下一篇  2011-07-02 17:55:29 / 个人分类:selenium2

http://www.openwritings.net/public/selenium-2/overloading-findelement-add-waiting-time

Update: 2010-08-05:
It looks like overloading findElements() to add a wait time is no longer required. As of version 2.0a5, you can useRemoteWebDriver.RemoteTimeouts.implicitlyWait() like the following:
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS)



When you run your tests multiple times without changing any code, WebDriver sometimes fails to find elements. This may be caused by multiple factors such as the network connection speed, ajax, etc. For a detailed explanation, see here. Due to these problems, I decided to make findElement() more fault tolerant. Therefore, I overload findElement() to add a waiting time. It will keep waiting until the element is found or a timeout is expired.

/**
 * Before finding the element, keep waiting until the element is found or a timeout is expired.
 * @param webDriver
 * @param by
 * @param timeout Timeout in milliseconds.
 * @return Return the WebElement found.
 */privateWebElement findElement(WebDriver webDriver, By by,inttimeout){intiSleepTime=1000;for(inti=0;i<timeout;i+=iSleepTime){List<WebElement>oWebElements=webDriver.findElements(by);if(oWebElements.size()>0){returnoWebElements.get(0);}else{try{Thread.sleep(iSleepTime);System.out.println(String.format("%s: Waited for %d milliseconds.[%s]",newjava.util.Date().toString(), i+iSleepTime, by));}catch(InterruptedExceptionex){thrownewRuntimeException(ex);}}} // Can't find 'by' element. Therefore throw an exception.StringsException=String.format("Can't find %s after %d milliseconds.", by, timeout);thrownewRuntimeException(sException);}

TAG:

 

评分:0

我来说两句

Open Toolbar