How do I set the Selenium webdriver get timeout?


We can set the Selenium webdriver to get timeout. There are numerous methods to implement timeouts. They are listed below −

  • setScriptTimeout.

  • pageLoadTimeout.

  • implicitlyWait.

The setScriptTimeout is the method to set the time for the webdriver. This is usually applied for an asynchronous test to complete prior throwing an exception. The default value of timeout is 0.

This method is generally used for JavaScript commands in Selenium. If we omit setting time for the script, the executeAsyncScript method can encounter failure due to the more time consumed by the JavaScript to complete execution.

If the timeout time is set to negative, then the JavaScript can execute for an endless time.

Syntax

driver.manage().timeouts().setScriptTimeout(5,TimeUnit.SECONDS);

The pageLoadTimeout is the method used to set the time for the entire page load prior to throwing an exception. If the timeout time is set to negative, then the time taken to load the page is endless.

This timeout is generally used with the navigate and manage methods.

Syntax

driver.manage().timeouts().pageLoadTimeout(4, TimeUnit.SECONDS);

Example

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class PageLoadWt{
   public static void main(String[] args)
   throws InterruptedException{
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //set time for page load
      driver.manage().timeouts().pageLoadTimeout(4, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      driver.quit();
   }
}

The implicitlyWait is the method applied to the webdriver to wait for elements to be available in the page. It is a global wait to every element. NoSuchElementException is thrown if an element is still not available after the wait time has elapsed.

Syntax

driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

Example

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ImplicitWt{
   public static void main(String[] args)
   throws InterruptedException{
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //set implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      driver.quit();
   }
}

Updated on: 01-Feb-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements