Skip to content

Make Selenium Easy

And Keep It That Way

  • Home
  • Share
  • Toggle search form

Using Thread.sleep() in Selenium WebDriver

Posted on 02/19/2025 By admin

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”.

  • 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.

  1. Thread.sleep() method – Provided by Java
  2. Implicit wait – Provided by Selenium WebDriver
  3. Explicit wait (WebDriverWait & FluentWait) Provided by Selenium WebDriver
  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)
  • 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

Uncategorized

Post navigation

Previous Post: Interview Experience
Next Post: FluentWait Vs WebDriverWait in Selenium WebDriver

Related Posts

Selenium Interview Question 8 – What is Difference between WebDriver click and JavaScript click methods Uncategorized
Handling JQuery Dialog Box In Selenium Webdriver Uncategorized
December 16, 2017 – Make Selenium Easy Uncategorized
Postman Tutorial Part 44 – Data Driven Testing in Postman Using CSV File Uncategorized
Make Selenium Easy | Make Selenium Easy – Selenium Tutorials : End To End Uncategorized
API Testing Tutorial Part 10 – Introduction of SOAP (Simple Object Access Protocol) Uncategorized

Recent Posts

  • Getting Started with Selenium 4: What Is New and How to Upgrade from Selenium 3
  • Manual Testing
  • Baby Steps To Become Efficient Selenium-Java Automation Tester
  • Features of Selenium 4.0.0 Release – Java Binding
  • Part 1: Handling Drop-down Created Using SELECT Tag In Selenium

Recent Comments

No comments to show.

Archives

  • April 2026
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • April 2024
  • March 2024
  • February 2024
  • December 2023
  • October 2023
  • August 2023
  • November 2022
  • September 2022
  • August 2022
  • July 2022
  • May 2022
  • March 2022
  • October 2021
  • April 2021
  • March 2021
  • January 2021
  • December 2020
  • October 2020
  • September 2020
  • August 2020
  • June 2020
  • May 2020
  • April 2020
  • March 2020
  • February 2020
  • January 2020
  • December 2019
  • November 2019
  • October 2019
  • September 2019
  • August 2019
  • May 2019
  • December 2018
  • November 2018
  • October 2018
  • September 2018
  • August 2018
  • July 2018
  • January 2018

Categories

  • Getting Started
  • Uncategorized

Copyright © 2026 Make Selenium Easy.

Powered by PressBook Masonry Dark