How to stop selenium webdriver from waiting for page load?

12.7k views Asked by At

Sometimes when i run a test, website never stops loading and my test stucks on it. How can i set driver.get() method to not wait for page load? If its impossible are there any work arounds or other methods that could replace driver.get()?

2

There are 2 answers

1
JimEvans On BEST ANSWER

The easiest way to exit the page load wait early is to set the page load timeout. When the timeout expires, you can catch the TimeoutException and proceed with the next step of your test. The code to invoke this would look something like the following:

// Set the page load timeout to 10 seconds.
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);

try {
  driver.get("http://url/to/my/slow/loading/page");
} catch (TimeoutException e) {
  // Ignore the exception.
}

// Proceed with your next step here.

Note that you may have to use a WebDriverWait or similar to ensure the element you're interested in is present on the page.

0
Jlearner On

We can set pageLoadTimeout, once set it wil be there throught the webdriver session, and if the exception is thrown because of timeout then we can't restore same session so need to create new instance.

        WebDriver driver = new FirefoxDriver();

        //waits 10 seconds for page to load
        driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
        try {
            driver.get("https://yourdomain.com");
        } catch (TimeoutException e) {
            driver.close();
            driver.quit();

            //create new instance of webdriver
            driver = new FirefoxDriver();

            //waits 5 minutes for page to load
            driver.manage().timeouts().pageLoadTimeout(300, TimeUnit.SECONDS);
            driver.get("https://yourdomain.com");
        }