Using Thread.sleep() in Selenium WebDriver

Agenda:

  1. Need of wait statements in Selenium WebDriver scripts
  2. Introduction of NoSuchElementException
  3. Types of wait provided by Java and Selenium WebDriver
  4. Introduction of Thread.sleep() method
  5. Working of Thread.sleep()
  6. Disadvantages of using Thread.sleep() in selenium scripts

Let’s write a simple selenium WebDriver scripts as per given scenario :-

  1. Launch a chrome browser.
  2. Load “https://www.redbus.in/” URL.
  3. Locate and type “Ban” in “From” text box.
  4. Click on Bangalore from search result.
  5. Close the browser.

Lets write code for above scenario:

package WaitExamples;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class UsageOfSleep {

	public static void main(String[] args) {

		// Setting up browser executable using WebDriverManager
		WebDriverManager.chromedriver().setup();
		// Opening a browser and maximizing
		WebDriver driver = new ChromeDriver();
		driver.manage().window().maximize();
		// Loading a URL
		driver.get("https://www.redbus.in/");
		// Locating and typing in From text box.
		WebElement fromTextBox = driver.findElement(By.id("src"));
		fromTextBox.sendKeys("Ban");
		// Clicking on first search result
		driver.findElement(By.xpath("//li[@select-id='results[0]']")).click();
		// Closing browser
		driver.quit();

	}

}

Run the code and observe output.

Output :-

Starting ChromeDriver 80.0.3987.106 (f68069574609230cf9b635cd784cfb1bf81bb53a-refs/branch-heads/3987@{#882}) on port 33438
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//li[@select-id='results[0]']"}
  (Session info: chrome=80.0.3987.163)
For documentation on this error, please visit: https://selenium.dev/exceptions/#no_such_element
Build info: version: '4.0.0-alpha-5', revision: 'b3a0d621cc'
System info: host: 'WKWIN6962993', ip: '192.168.0.6', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_231'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, browserName: chrome, browserVersion: 80.0.3987.163, chrome: {chromedriverVersion: 80.0.3987.106 (f68069574609..., userDataDir: C:\Users\amomahaj\AppData\L...}, goog:chromeOptions: {debuggerAddress: localhost:50867}, javascriptEnabled: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: WINDOWS, platformName: WINDOWS, proxy: Proxy(), setWindowRect: true, strictFileInteractability: false, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unhandledPromptBehavior: dismiss and notify}
Session ID: 597324785060a249aaa4b63ea758bcf1
*** Element info: {Using=xpath, value=//li[@select-id='results[0]']}
	at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
	at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:196)
	at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:129)
	at org.openqa.selenium.remote.codec.w3c.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:53)
	at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:161)
	at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
	at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:582)
	at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:333)
	at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:451)
	at org.openqa.selenium.By$ByXPath.findElement(By.java:394)
	at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:325)
	at WaitExamples.UsageOfSleep.main(UsageOfSleep.java:25)

As we can see a NoSuchElementException is thrown and exception occurred at line no 25 above. In short WebDriver was not able to find search result in drop down after typing search input as “Ban”.

About NoSuchElementException?

  • NoSuchElementException is a sub class of RuntimeException.
  • It is a unchecked exception.
  • It is thrown by findElement(By by) method above. Note here I mentioned only findElement() method not findElements() methodas it gives you an empty array rather than exception.
  • It is thrown when WebDriver is not able to locate an element for some reasons. It might be wrong locator or element is not loaded yet.

So, we got basic idea about NoSuchElementException.

Let’s analyse what causes our program to throw NoSuchElementException.

Let’s try it manually. When we typed “ban” in “From” text box and after SOME SECONDS it displays search result. And then we clicked on first search result. When same steps were done by WebDriver , it did not know that it had to wait for search results to appear and we did not let WebDriver know to wait and it throws NoSuchElementException.

Different ways of making WebDriver to wait :-

  1. Thread.sleep() method – Provided by Java
  2. Implicit wait – Provided by Selenium WebDriver
  3. Explicit wait (WebDriverWait & FluentWait) Provided by Selenium WebDriver

Thread.sleep() method :-

  1. Thread is a class in JAVA.
  2. sleep() is a static method of Thread class so we can use it using class name i.e. Thread.
  3. Thread.sleep causes the current thread to suspend execution for a specified period.
  4. sleep() methods accept duration in miliseconds. ( 1 s= 1000 ms).
  5. It throws  IllegalArgumentException – if the value of millis is negative.
  6. sleep() throws a checked exception which we must either throw or handle it using try catch.
  7. Syntax: Thread.sleep(3000);
  8. It is a static wait. Execution will be on hold till specified time.

So you should note here that sleep() is not provided by Selenium WebDriver, so it is not a selenium wait.

So now we know one way of making selenium WebDriver to wait. Let’s implement it. We should add sleep() method where it is required. We know after typing “BAN” in From text box we need to make WebDriver wait. Lets put a sleep statement there.

package WaitExamples;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

public class UsageOfSleep {

	public static void main(String[] args) throws InterruptedException {

		// Setting up browser executable using WebDriverManager
		WebDriverManager.chromedriver().setup();
		// Opening a browser and maximizing
		WebDriver driver = new ChromeDriver();
		driver.manage().window().maximize();
		// Loading a URL
		driver.get("https://www.redbus.in/");
		// Locating and typing in From text box.
		WebElement fromTextBox = driver.findElement(By.id("src"));
		fromTextBox.sendKeys("Ban");
		// Put a sleep wait
		Thread.sleep(5000);
		// Clicking on first search result
		driver.findElement(By.xpath("//li[@select-id='results[0]']")).click();
		// Let's print the select value
		String selectedCity = driver.findElement(By.id("src")).getAttribute("value");
		System.out.println("Selected city in From is :"+selectedCity);
		// Closing browser
		driver.quit();
	}

}

Output :-

Starting ChromeDriver 80.0.3987.106 (f68069574609230cf9b635cd784cfb1bf81bb53a-refs/branch-heads/3987@{#882}) on port 8987
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Bangalore (All Locations)

Disadvantages of Thread.sleep() method:

  • We make WebDriver to wait for 5 seconds in above program. What if search result appears in just a second? WebDriver will still wait for another 4 seconds. It will increase test execution time.
  • We need to pass wait time in advance to sleep method. What if search result appears after 6 seconds. Our script will fail again. We can not keep updating scripts with different values.

But sometimes you may face a scenario where none of waits provided by Selenium WebDriver works. Let me share you a real time example experienced by me.

There were tiles on application’s home page and when that application is loaded in browser, all tiles auto adjust quickly based on count of items on those tiles . Selenium scripts need to click on those tiles and sometimes clicking on tiles was not working although it clicked but not at correct place because of quick loading. We tried all types of mechanism but none worked. Element used to be well visible and ready to get clicked and page load status is also completed. We added a retry mechanism but as application was so dynamic that what will come after clicking on tiles was not known in advance. But still we added retry mechanism with a lot of logic which took more time to start actual test. We observed putting a sleep of 3 seconds make test faster rather than check for a visibility of an element at landing page and then retry. So I think if you use sleep wisely it can solve problems. You can not completely avoid sleep sometimes and moreover wait mechanisms in Selenium WebDriver also uses sleep() method as a default sleeper. So if they can use it dynamically, why can’t we. Think on it.

You can clone the above example from my repo.

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
#ThanksForReading
#HappyLearning

You can find all Selenium related post here.
You can find all API manual and automation related posts here.
You can find frequently asked Java Programs here.

17 thoughts on “Using Thread.sleep() in Selenium WebDriver

  1. Very nice, in detail explanation given. Thanks.

    I’m begginner in Automation Testing. Could you please refer me some learning videos.
    It would be a great help.

    1. Thanks Nikhil. You can view Mukesh Otwani youtube videos. Also you can follow my blog from first post.

Leave a Reply

Your email address will not be published. Required fields are marked *