use*_*173 5 selenium selenium-webdriver
在webdriver代码,如果我使用thread.sleep(20000).它等了20秒,我的代码也运行正常.如果我使用隐式等待,则归档相同
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Run Code Online (Sandbox Code Playgroud)
它没有等待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"));
}
});
Run Code Online (Sandbox Code Playgroud)
但是,如果我说错了ID,它会等待50秒但是其他测试没有点击就通过了......它没有显示任何错误.
我的问题是我应该如何避免,Thread.sleep()因为其他硒方法没有帮助我..
使用以下方法等待元素:
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;
}
Run Code Online (Sandbox Code Playgroud)
下面的方法是等待页面加载:
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);
}
Run Code Online (Sandbox Code Playgroud)
假设您正在等待页面加载。然后调用第一个方法并等待一段时间,并且页面加载后出现的任何元素都会返回true,否则false。使用它就像,
waitForElementToBePresent(By.id("Something"), 20000)
Run Code Online (Sandbox Code Playgroud)
上面调用的函数会等待,直到在给定的持续时间内找到给定的元素。
在上述方法之后尝试以下任何代码
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id<locator>));
Run Code Online (Sandbox Code Playgroud)
或者
wait.until(ExpectedConditions.elementToBeClickable(By.id<locator>));
Run Code Online (Sandbox Code Playgroud)
更新:
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;
}
Run Code Online (Sandbox Code Playgroud)
这将尝试在文本字段中输入文本,直到给定时间(以毫秒为单位)。如果getAttribute()不适合您的情况使用getText()。如果输入文本则返回 true。输入您可以等待的最长时间。
| 归档时间: |
|
| 查看次数: |
3663 次 |
| 最近记录: |