如何让Selenium 2.0等待页面加载?
当前回答
最简单的方法就是等待一些元素出现在加载页面上。
如果你想在页面加载后点击一些按钮,你可以使用等待,然后点击:
await().until().at.most(20, TimeUnit.Seconds).some_element.isDisplayed(); // or another condition
getDriver().find(some_element).click;
其他回答
最简单的方法就是等待一些元素出现在加载页面上。
如果你想在页面加载后点击一些按钮,你可以使用等待,然后点击:
await().until().at.most(20, TimeUnit.Seconds).some_element.isDisplayed(); // or another condition
getDriver().find(some_element).click;
对于隐式等待,你可以使用如下代码:
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS)
为了使网页等待一个特定的对象是可见的或某些条件是真实的。您可以使用网页驱动程序等羽。
//120 is maximum number of seconds to wait.
WebDriverWait wait = new WebDriverWait(driver,120);
wait.until(ExpectedConditions.elementToBeClickable("CONDITITON"));
在Java中,另一种选择是让线程在特定的时间内休眠。
Thread.sleep(numberOfSeconds*1000);
//This line will cause thread to sleep for seconds as variable
我创建了一个方法来简化线程。睡眠的方法
public static void wait_time(int seconds){
try {
Thread.sleep(seconds*1000);
}catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
使用wait_time(10)方法;线程将休眠10秒。
你可以使用等待。硒中基本上有两种类型的等待
隐式等 显式等
-隐式等待
这很简单,请参阅下面的语法:
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
-显式等待
在此等待中显式等待或有条件等待,直到给定条件发生。
WebDriverWait wait = new WebDriverWait(driver, 40);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
您可以使用其他属性,如visblityOf(), visblityOfElement()
如何让Selenium在单击后等待页面加载提供了以下有趣的方法:
存储旧页面中对WebElement的引用。 点击链接。 继续调用WebElement上的操作,直到抛出StaleElementReferenceException。
示例代码:
WebElement link = ...;
link.click();
new WebDriverWait(webDriver, timeout).until((org.openqa.selenium.WebDriver input) ->
{
try
{
link.isDisplayed();
return false;
}
catch (StaleElementReferenceException unused)
{
return true;
}
});
使用下面的代码,它是非常容易和简单的页面加载。
public void PageLoad(IWebDriver driver, By by)
{
try
{
Console.WriteLine("PageLoad" + by);
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.ElementIsVisible(by));
wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30)); // 30 seconds wait until element not found.
wait.Until(ExpectedConditions.ElementToBeClickable(by));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Assert.Fail("Element not found!")
}
}
我希望这对你有所帮助。
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap