我正在使用 Selenium2(2.0-b3) 网络驱动程序 我想等待页面上出现一个元素。我可以像下面这样写,效果很好。
但我不想为每个页面都放置这些 block 。
// 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;
}
});
我想将其转换为一个可以传递 elementid 的函数,该函数等待指定的时间,并根据是否找到元素返回 true 或 false。
public static boolean waitForElementPresent(WebDriver 驱动程序,String elementId,int noOfSecToWait){
}
我读到等待在页面加载等之前不会返回,但我想编写上述方法,以便我可以单击页面链接并调用 waitForElementPresent 方法以在执行任何操作之前等待下一页中的元素与页面。
你能帮我写这个方法吗,我遇到了问题,因为我不知道如何重构上述方法以便能够传递参数。
谢谢 迈克
最佳答案
这就是我在 C# 中执行此操作的方法(每 250 毫秒检查一次元素是否出现):
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;
}
像这样调用函数:
bool found = WaitForElementPresent(By.Id("resultStats"), 5); //Waits 5 seconds
这有帮助吗?
关于wait - Selenium2 等待页面上的特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6160069/