如果我使用thread.sleep(20000)的话。它等待了20秒,而我的代码也运行得很好。在使用隐式等待的情况下进行归档,例如
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); 它不会强制等待20秒,只需3到4秒就可以进入下一步。页面仍在加载中。
这是有线的情况,因为我正在使用流畅的等待来寻找一些元素。如果元素仍在页面上加载,则不会显示错误,并使测试通过。
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(50, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("jxxx"));
}
});但是如果我输入了错误的id,它会等待50秒,但其他测试在没有单击的情况下就通过了。它没有显示任何错误。
我的问题是,我应该如何避免Thread.sleep(),因为其他selenium方法对我没有帮助。
发布于 2013-04-16 00:47:03
使用下面的方法等待一个元素:
public boolean waitForElementToBePresent(By by, int waitInMilliSeconds) throws Exception
{
int wait = waitInMilliSeconds;
int iterations = (wait/250);
long startmilliSec = System.currentTimeMillis();
for (int i = 0; i < iterations; i++)
{
if((System.currentTimeMillis()-startmilliSec)>wait)
return false;
List<WebElement> elements = driver.findElements(by);
if (elements != null && elements.size() > 0)
return true;
Thread.sleep(250);
}
return false;
}下面的方法是等待页面加载:
public void waitForPageLoadingToComplete() throws Exception {
ExpectedCondition<Boolean> expectation = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript(
"return document.readyState").equals("complete");
}
};
Wait<WebDriver> wait = new WebDriverWait(driver, 30);
wait.until(expectation);
}让我们假设您正在等待页面加载。然后调用第一个方法,带等待时间和页面加载后出现的任何元素,然后它将返回true,否则返回false。像这样使用它,
waitForElementToBePresent(By.id("Something"), 20000)上面调用的函数等待,直到它在给定的持续时间内找到给定的元素。
在上面的方法之后尝试下面的任何代码
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));或
wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));更新:
public boolean waitForTextFiled(By by, int waitInMilliSeconds, WebDriver wdriver) throws Exception
{
WebDriver driver = wdriver;
int wait = waitInMilliSeconds;
int iterations = (wait/250);
long startmilliSec = System.currentTimeMillis();
for (int i = 0; i < iterations; i++)
{
if((System.currentTimeMillis()-startmilliSec)>wait)
return false;
driver.findElement(By.id("txt")).sendKeys("Something");
String name = driver.findElement(by).getAttribute("value");
if (name != null && !name.equals("")){
return true;
}
Thread.sleep(250);
}
return false;
}这将尝试在文本字段中输入文本,直到在millis中指定时间。如果getAttribute()不适合您的情况,请使用getText()。如果文本为enetered,则返回true。放置你可以等待的最大时间。
发布于 2013-04-16 10:12:17
您可能希望尝试此操作,以使元素在屏幕上变为可见。
new WebDriverWait(10, driver).until(ExpectedConditions.visibilityOfElementLocated(By.id("jxxx")).在这种情况下,等待时间最长为10秒。
https://stackoverflow.com/questions/16016120
复制相似问题