How do you make Selenium 2.0 wait for the page to load?

You can also check pageloaded using following code

IWait<IWebDriver> wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(30.00));

 wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
2017年12月07日38分14秒 Use class WebDriverWait Also see here You can expect to show some element. something like in C#: WebDriver _driver = new WebDriver();
WebDriverWait _wait = new WebDriverWait(_driver, new TimeSpan(0, 1, 0)); _wait.Until(d => d.FindElement(By.Id("Id_Your_UIElement"));
2017年12月07日38分14秒 If you set the implicit wait of the driver, then call the findElement method on an element you expect to be on the loaded page, the WebDriver will poll for that element until it finds the element or reaches the time out value. driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
source: implicit-waits 2017年12月07日38分14秒 In general, with Selenium 2.0 the web driver should only return control to the calling code once it has determined that the page has loaded. If it does not, you can call waitforelemement, which cycles round calling findelement until it is found or times out (time out can be set). 2017年12月07日38分14秒 Ruby implementation: wait = Selenium::WebDriver::Wait.new(:timeout => 10)
wait.until {
@driver.execute_script("return document.readyState;") == "complete"
}
2017年12月07日38分14秒 You may remove the System.out line. It is added for debug purposes. WebDriver driver_; public void waitForPageLoad() { Wait<WebDriver> wait = new WebDriverWait(driver_, 30);
wait.until(new Function<WebDriver, Boolean>() {
public Boolean apply(WebDriver driver) {
System.out.println("Current Window State : "
+ String.valueOf(((JavascriptExecutor) driver).executeScript("return document.readyState")));
return String
.valueOf(((JavascriptExecutor) driver).executeScript("return document.readyState"))
.equals("complete");
}
});
}
2017年12月07日38分14秒 You can also use the class: ExpectedConditions to explicitly wait for an element to show up on the webpage before you can take any action further actions You can use the ExpectedConditions class to determine if an element is visible: WebElement element = (new WebDriverWait(getDriver(), 10)).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input#houseName")));
See ExpectedConditions class Javadoc for list of all conditions you are able to check. 2017年12月07日38分14秒 This seems to be a serious limitation of WebDriver. Obviously waiting for an element will not imply the page being loaded, in particular the DOM can be fully build (onready state) whereby JS is still executing and CSS and images are still loading. I believe the simplest solution is to set a JS variable upon the onload event after everything is initialized and check and wait for this JS variable in Selenium. 2017年12月07日38分14秒 All of these solutions are OK for specific cases, but they suffer from at least one of a couple of possible problems: They are not generic enough -- they want you to know, ahead of time, that some specific condition will be true of the page you are going to (eg some element will be displayed) They are open to a race condition where you use an element that is actually present on the old page as well as the new page. Here's my attempt at a generic solution that avoids this problem (in Python): First, a generic "wait" function (use a WebDriverWait if you like, I find them ugly): def wait_for(condition_function):
start_time = time.time()
while time.time() < start_time + 3:
if condition_function():
return True
else:
time.sleep(0.1)
raise Exception('Timeout waiting for {}'.format(condition_function.__name__))
Next, the solution relies on the fact that selenium records an (internal) id-number for all elements on a page, including the top-level <html> element. When a page refreshes or loads, it gets a new html element with a new ID. So, assuming you want to click on a link with text "my link" for example: old_page = browser.find_element_by_tag_name('html') browser.find_element_by_link_text('my link').click() def page_has_loaded():
new_page = browser.find_element_by_tag_name('html')
return new_page.id != old_page.id wait_for(page_has_loaded)
For more Pythonic, reusable, generic helper, you can make a context manager: from contextlib import contextmanager @contextmanager
def wait_for_page_load(browser):
old_page = browser.find_element_by_tag_name('html') yield def page_has_loaded():
new_page = browser.find_element_by_tag_name('html')
return new_page.id != old_page.id wait_for(page_has_loaded)
And then you can use it on pretty much any selenium interaction: with wait_for_page_load(browser):
browser.find_element_by_link_text('my link').click()
I reckon that's bulletproof! What do you think? More info in a blog post about it here 2017年12月07日38分14秒 If you want to wait for a specific element to load, you can use the isDisplayed() method on a RenderedWebElement : // Sleep until the div we want is visible or 5 seconds is over
long end = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < end) {
// Browsers which render content (such as Firefox and IE) return "RenderedWebElements"
RenderedWebElement resultsDiv = (RenderedWebElement) driver.findElement(By.className("gac_m")); // If results have been returned, the results are displayed in a drop down.
if (resultsDiv.isDisplayed()) {
break;
}
}
(Example from The 5 Minute Getting Started Guide) 2017年12月07日38分14秒 Imran's answer rehashed for Java 7: WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver wdriver) {
return ((JavascriptExecutor) driver).executeScript(
"return document.readyState"
).equals("complete");
}
});
2017年12月07日38分14秒 I'm surprised that predicates weren't the first choice as you typically know what element(s) you will next interact with on the page you're waiting to load. My approach has always been to build out predicates/functions like waitForElementByID(String id) and waitForElemetVisibleByClass(String className), etc. and then use and reuse these wherever I need them, be it for a page load or page content change I'm waiting on. For example, In my test class: driverWait.until(textIsPresent("expectedText");
In my test class parent: protected Predicate<WebDriver> textIsPresent(String text){
final String t = text;
return new Predicate<WebDriver>(){
public boolean apply(WebDriver driver){
return isTextPresent(t);
}
};
} protected boolean isTextPresent(String text){
return driver.getPageSource().contains(text);
}
Though this seems like a lot, it takes care of checking repeatedly for you and the interval for how often to check can be set along with the ultimate wait time before timing out. Also, you will reuse such methods. In this example, the parent class defined and initiated the WebDriver driver and the WebDriverWait driverWait. I hope this helps. 2017年12月07日38分14秒 Use implicitly wait for wait of every element on page till given time. driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
this wait for every element on page for 30 sec. Another wait is Explicitly wait or conditional wait in this wait until given condition. WebDriverWait wait = new WebDriverWait(driver, 40);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
In id give static element id which is diffidently display on the page, as soon as page is load. 2017年12月07日38分14秒 /**
* Call this method before an event that will change the page.
*/
private void beforePageLoad() {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.mpPageReloaded='notYet';");
} /**
* Call this method after an event that will change the page.
*
* @see #beforePageLoad
*
* Waits for the previous page to disappear.
*/
private void afterPageLoad() throws Exception {
(new WebDriverWait(driver, 10)).until(new Predicate<WebDriver>() { @Override
public boolean apply(WebDriver driver) {
JavascriptExecutor js = (JavascriptExecutor) driver;
Object obj = js.executeScript("return document.mpPageReloaded;");
if (obj == null) {
return true;
}
String str = (String) obj;
if (!str.equals("notYet")) {
return true;
}
return false;
}
});
}
You can change from the document to an element, in the case of where only part of a document is being changed. This technique was inspired by the answer from sincebasic. 2017年12月07日38分14秒 SeleniumWaiter: import com.google.common.base.Function;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait; public class SeleniumWaiter { private WebDriver driver; public SeleniumWaiter(WebDriver driver) {
this.driver = driver;
} public WebElement waitForMe(By locatorname, int timeout){
WebDriverWait wait = new WebDriverWait(driver, timeout);
return wait.until(SeleniumWaiter.presenceOfElementLocated(locatorname));
} public static Function<WebDriver, WebElement> presenceOfElementLocated(final By locator) {
// TODO Auto-generated method stub
return new Function<WebDriver, WebElement>() {
@Override
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
};
}
}
And to you use it: _waiter = new SeleniumWaiter(_driver); try {
_waiter.waitForMe(By.xpath("//..."), 10);
}
catch (Exception e) {
// Error
}
2017年12月07日38分14秒 You can explicitly wait for an element to show up on the webpage before you can take any action (like element.click()) driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(new ExpectedCondition<WebElement>(){
@Override
public WebElement apply(WebDriver d) {
return d.findElement(By.id("myDynamicElement"));
}});
This is what I used for a similar scenario and it works fine. 2017年12月07日38分14秒 My simple way: long timeOut = 5000;
long end = System.currentTimeMillis() + timeOut; while (System.currentTimeMillis() < end) { if (String.valueOf(
((JavascriptExecutor) driver)
.executeScript("return document.readyState"))
.equals("complete")) {
break;
}
}
2017年12月07日38分14秒 The best way to wait for page loads when using the Java bindings for WebDriver is to use the Page Object design pattern with PageFactory. This allows you to utilize the AjaxElementLocatorFactory which to put it simply acts as a global wait for all of your elements. It has limitations on elements such as drop-boxes or complex javascript transitions but it will drastically reduce the amount of code needed and speed up test times. A good example can be found in this blogpost. Basic understanding of Core Java is assumed. http://startingwithseleniumwebdriver.blogspot.ro/2015/02/wait-in-page-factory.html 2017年12月07日38分14秒 NodeJS Solution: In Nodejs you can get it via promises... If you write this code, you can be sure that the page is fully loaded when you get to the then... driver.get('www.sidanmor.com').then(()=> {
// here the page is fully loaded!!!
// do your stuff...
}).catch(console.log.bind(console));
If you write this code, you will navigate, and selenium will wait 3 seconds... driver.get('www.sidanmor.com');
driver.sleep(3000);
// you can't be sure that the page is fully loaded!!!
// do your stuff... hope it will be OK...
From Selenium documentation: this.get( url ) → Thenable Schedules a command to navigate to the given URL. Returns a promise that will be resolved when the document has finished loading. Selenium Documentation (Nodejs) 2017年12月07日38分14秒 You can use the below existing method to set the time for pageeLoadTimeout in below example if the page is taking more than 20 seconds to load , then it will throw an exception of page reload WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS)
2017年12月07日38分14秒 Explicitly wait or conditional wait in this wait until given condition. WebDriverWait wait = new WebDriverWait(wb, 60);
wait.until(ExpectedConditions.elementToBeClickable(By.name("value")));
This will wait for every web element for 60 seconds. Use implicitly wait for wait of every element on page till given time. driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
This will wait for every web element for 60 seconds. Both works fine. But my personal favorite is Explicitly wait because it is more stable one 2017年12月07日38分14秒 You can use wait. there are basically 2 types of wait in selenium Implicit wait
Explicit wait
- Implicit wait This is very simple please see syntax below: driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
- Explicit wait Explicitly wait or conditional wait in this wait until given condition is occurred. WebDriverWait wait = new WebDriverWait(driver, 40);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
You can use other properties like visblityOf(), visblityOfElement() 2017年12月07日38分14秒 driver.asserts().assertElementFound("Page was not loaded",
By.xpath("//div[@id='actionsContainer']"),Constants.LOOKUP_TIMEOUT);
2017年12月07日38分14秒 The easiest way is just wait for some element which will appear on loaded page. If you would like to click on some button already after page is loaded you could use await and click: await().until().at.most(20, TimeUnit.Seconds).some_element.isDisplayed(); // or another condition
getDriver().find(some_element).click;
2017年12月07日38分14秒 How to get Selenium to wait for page load after a click provides the following interesting approach: Store a reference to a WebElement from the old page.
Click the link.
Keep on invoking operations on the WebElement until StaleElementReferenceException is thrown.
Sample code: WebElement link = ...;
link.click();
new WebDriverWait(webDriver, timeout).until((org.openqa.selenium.WebDriver input) ->
{
try
{
link.isDisplayed();
return false;
}
catch (StaleElementReferenceException unused)
{
return true;
}
});
2017年12月07日38分14秒 use a if condition and for any of the element present try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
2017年12月07日38分14秒 You can try this code to let the page load completely until element is found. public void waitForBrowserToLoadCompletely() {
String state = null;
String oldstate = null;
try {
System.out.print("Waiting for browser loading to complete"); int i = 0;
while (i < 5) {
Thread.sleep(1000);
state = ((JavascriptExecutor) driver).executeScript("return document.readyState;").toString();
System.out.print("." + Character.toUpperCase(state.charAt(0)) + ".");
if (state.equals("interactive") || state.equals("loading"))
break;
/*
* If browser in 'complete' state since last X seconds. Return.
*/ if (i == 1 && state.equals("complete")) {
System.out.println();
return;
}
i++;
}
i = 0;
oldstate = null;
Thread.sleep(2000); /*
* Now wait for state to become complete
*/
while (true) {
state = ((JavascriptExecutor) driver).executeScript("return document.readyState;").toString();
System.out.print("." + state.charAt(0) + ".");
if (state.equals("complete"))
break; if (state.equals(oldstate))
i++;
else
i = 0;
/*
* If browser state is same (loading/interactive) since last 60
* secs. Refresh the page.
*/
if (i == 15 && state.equals("loading")) {
System.out.println("\nBrowser in " + state + " state since last 60 secs. So refreshing browser.");
driver.navigate().refresh();
System.out.print("Waiting for browser loading to complete");
i = 0;
} else if (i == 6 && state.equals("interactive")) {
System.out.println(
"\nBrowser in " + state + " state since last 30 secs. So starting with execution.");
return;
} Thread.sleep(4000);
oldstate = state; }
System.out.println(); } catch (InterruptedException ie) {
ie.printStackTrace();
}
}
2017年12月07日38分14秒 private static void checkPageIsReady(WebDriver driver) {
JavascriptExecutor js = (JavascriptExecutor) driver; // Initially bellow given if condition will check ready state of page.
if (js.executeScript("return document.readyState").toString().equals("complete")) {
System.out.println("Page Is loaded.");
return;
} // This loop will rotate for 25 times to check If page Is ready after
// every 1 second.
// You can replace your value with 25 If you wants to Increase or
// decrease wait time.
for (int i = 0; i < 25; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
// To check page ready state.
if (js.executeScript("return document.readyState").toString().equals("complete")) {
break;
}
}
}
2017年12月07日38分14秒 You can use this snippet of code for the page to load: IWait wait = new OpenQA.Selenium.Support.UI.WebDriverWait(driver,TimeSpan.FromSeconds(30.00));
wait.Until(driver1 => ((IJavaScriptExecutor)driver).ExecuteScript("return document.readyState").Equals("complete"));
Or you can use waiter for any element to be loaded and become visible/clickable on that page, most probably which is going to be load at the end of loading like: Wait.Until(ExpectedConditions.ElementToBeClickable(By.XPath(xpathOfElement));
var element = GlobalDriver.FindElement(By.XPath(xpathOfElement));
var isSucceededed = element != null;
2017年12月07日38分14秒 The best way I've seen is to utilize the stalenessOf ExpectedCondition, to wait for the old page to become stale. Example: WebDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 10); WebElement oldHtml = driver.findElement(By.tagName("html"));
wait.until(ExpectedConditions.stalenessOf(oldHtml));
It'll wait for ten seconds for the old HTML tag to become stale, and then throw an exception if it doesn't happen. 2017年12月07日38分14秒

  

判断Selenium加载完成的更多相关文章

  1. selenium加载时间过长

    为了获取网站js渲染后的html,需要利用selenium加载网站,但是会出现加载时间过长的现象,因此可以限制其加载时间以及强制关掉加载: # !/usr/bin/python3.4 # -*- co ...

  2. 动态加载JS过程中如何判断JS加载完成

    在正常的加载过程中,js文件的加载是同步的,也就是说在js加载的过程中,浏览器会阻塞接下来的内容的解析.这时候,动态加载便显得尤为重要了,由于它是异步加载,因此,它可以在后台自动下载,并不会妨碍其它内 ...

  3. JS判断页面加载完毕

    //JS判断页面加载完毕,再隐藏加载效果层,一个简单的JS加载效果. document.onreadystatechange = function () { if (document.readySta ...

  4. js判断页面加载完毕方法

    判断页面加载完成这个方法是很常见的,下面有三个常用的方法,各有利弊. 一.纯js方法 // (1).页面所有内容加载完成执行 window.onload = function(){ } // (2). ...

  5. selenium 加载jquery

    packagecom.example.tests; import staticorg.junit.Assert.*; importjava.util.*; importorg.junit.*; imp ...

  6. 判断iframe加载完成

    一.js判断 var parFrame = document.getElementById("oIframe"); if(parFrame.attachEvent){ parFra ...

  7. [f]动态判断js加载完成

    在正常的加载过程中,js文件的加载是同步的,也就是说在js加载的过程中,浏览器会阻塞接下来的内容的解析.这时候,动态加载便显得尤为重要了,由于它是异步加载,因此,它可以在后台自动下载,并不会妨碍其它内 ...

  8. Duilib中Webbrowser事件完善使其支持判断页面加载完毕

    在多iframe的页面中,需要结合DISPID_DOCUMENTCOMPLETE和DISPID_NAVIGATECOMPLETE2两个事件判断页面是否加载完毕,而duilib中没有提供对DISPID_ ...

  9. Webbrowser控件判断网页加载完毕的简单方法 (转)

    摘自:http://blog.csdn.net/cometnet/article/details/5261192 一般情况下,当ReadyState属性变成READYSTATE_COMPLETE时,W ...

随机推荐

  1. jquery中的append功能相当于剪切的作用 将原来的元素剪切走

    jquery中的append功能相当于剪切的作用 将原来的元素剪切走

  2. bzoj4568-幸运数字

    题目 给出一棵树,每个节点上有权值\(a_i\),多次询问一条路径上选择一些点权值异或和最大值.\(n\le 2\times 10^4,q\le 2\times 10^5,0\le a_i\le 2\ ...

  3. wp开发(一)--应用发布篇

    本文非常简单,适合刚刚刚刚入门的菜鸟,且针对的是wp8版本.wp8应用的发布总体来说没什么难度,只是有几个值得注意的地方,希望本文可以减少菜鸟们不必要的担心. 首先假设项目已经完成,且要发布到应用商城 ...

  4. OSPF虚连接简单配置

    实验实例:<华为路由器学习指南>P715 本实例的拓扑结构如图:Area 2没有直接与骨干区域直接相连,Area 1被用作传输区域来连接Area 0与Area2.为了使Area2与骨干区域 ...

  5. java学习4-Maven的发布war并部署到tomcat

    1.点击生成-->Build Artifacts ,具体下图下图 2.生成完后会在target下出现一个war文件 3.部署到tomcat 复制war文件到tomcat/webapps,重启to ...

  6. 【BZOJ4129】Haruna’s Breakfast(树上莫队)

    [BZOJ4129]Haruna's Breakfast(树上莫队) 题面 BZOJ Description Haruna每天都会给提督做早餐! 这天她发现早饭的食材被调皮的 Shimakaze放到了 ...

  7. 基于三个kinect的人体建模

       单个kinect的人体重建,在Kinect SDK 1.8中,Kinect Fusion的效果已经很不错了.其缺点显而易见,一是扫描时间长,重建对象也需要长时间保持静态:二是需要人体或者kine ...

  8. 百万级运维心得一:Mongodb和Redis数据不能放在同一个服务器

    百万级运维经验一:Mongodb和Redis数据不能放在同一个服务器 一开始时,为了省服务器,把Mongodb和Redis放在一个服务器上.网站每到高峰期都特别卡,还经常出现502.找了很久的原因,发 ...

  9. Hbase(六) hbase Java API

    一. 几个主要 Hbase API 类和数据模型之间的对应关系: 1. HBaseAdmin关系: org.apache.hadoop.hbase.client.HBaseAdmin作用:提供了一个接 ...

  10. 常用Transformation算子

    map 产生的键值对是tupple,      split分隔出来的是数组 一.常用Transformation算子 (map  .flatMap .filter .groupByKey .reduc ...