Selenium2 wait for specific element on a page
I am using Selenium2(2.0-b3) web driver I want to wai开发者_如何学运维t for a element to be present on the page. I can write like below and it works fine.
But I do not want to put these blocks for every page.
// Wait for search to complete
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver webDriver) {
System.out.println("Searching ...");
return webDriver.findElement(By.id("resultStats")) != null;
}
});
I want to convert it into a function where I can pass elementid and the function waits for a specified time and returns me true of false based on element is found or not.
public static boolean waitForElementPresent(WebDriver driver, String elementId, int noOfSecToWait){
}
I am reading that wait does not return till page is loaded etc, but I want to write the above method so that i can click on link to a page and call waitForElementPresent method to wait for element in next page before I do anything with the page.
Can you please help me write the method, I am getting into issue because I do not know how to restructure the above method to be able to pass parameters.
Thanks Mike
This is how I do that in C# (checks every 250 milliseconds for the element to appear):
private bool WaitForElementPresent(By by, int waitInSeconds)
{
var wait = waitInSeconds * 1000;
var y = (wait/250);
var sw = new Stopwatch();
sw.Start();
for (var x = 0; x < y; x++)
{
if (sw.ElapsedMilliseconds > wait)
return false;
var elements = driver.FindElements(by);
if (elements != null && elements.count > 0)
return true;
Thread.Sleep(250);
}
return false;
}
Call the function like this:
bool found = WaitForElementPresent(By.Id("resultStats"), 5); //Waits 5 seconds
Does this help?
You can do like this, new a class and add below method:
public WebElement wait4IdPresent(WebDriver driver,final String elementId, int timeOutInSeconds){
WebElement we=null;
try{
WebDriverWait wdw=new WebDriverWait(driver, timeOutInSeconds);
if((we=wdw.until(new ExpectedCondition<WebElement>(){
/* (non-Javadoc)
* @see com.google.common.base.Function#apply(java.lang.Object)
*/
@Override
public WebElement apply(WebDriver d) {
// TODO Auto-generated method stub
return d.findElement(By.id(elementId));
}
}))!=null){
//Do something;
}
}catch(Exception e){
//Do something;
}
return we;
}
Do not try to implement interface ExpectedCondition<>, that's a bad idea. I got some problems before. :)
from here:
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(new ExpectedCondition<WebElement>(){
@Override
public WebElement apply(WebDriver d) {
return d.findElement(By.id("myDynamicElement"));
}});
精彩评论