Vishvambruth JT Vishvambruth JT - 2 months ago 24
Java Question

Need to write the selenium code without the Thread.sleep

I have written the below code to login to the website "".

The below code works just fine if i give Thread.sleep in between to make the code execution halt for some time.
If I comment the Thread.sleep, the code doesn't work as expected.
I have tried to use implicit and explicit waits of selenium to make driver to wait for the element to be visible but the code only works as expected when i use the Thread.sleep.

Is there any way I can make the below code to work without using the Thraed.Sleep statement.

and is it a bad practice to use Thread.sleep statements in the selenium code?

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class QTPSelenium {

public static WebDriver driver = null;

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

driver = new FirefoxDriver();

driver.findElement(By.xpath(".//*[@class='btn btn-default member_login']")).click();


driver.findElement("email")).sendKeys("Some Email ID");
driver.findElement("login-password")).sendKeys("Some Password");


Yes, it is generally bad practice to use Thread.sleep(). Sleeps aren't dynamic. They only wait for the specified time... no more, no less. This generally is not good because if the element you are waiting for comes back in 25ms, then you will wait the full 10s. If the element comes at 10.5s, then it will fail. With automation we want to go as fast as possible while maintaining consistent results. Using WebDriverWait will allow the script to pause and wait for the specified condition. Once the condition is met, the script continues. If it isn't met, the script will pause for the specified amount of time and retry until either the condition is met or a timeout occurs (throws an exception). So, make sure you wait as long as is reasonable to wait.

Instead use WebDriverWait, as I have below. Take a look at ExpectedConditions. There are many conditions you can wait for... presence of an element, element to be clickable, etc.

I switched to the geckodriver and tried the code again. I changed your locators to make them more specific. They are basically looking for a tag that contains certain text. You can reuse that locator several times. The code below is working for me. I removed the sleeps and replaced them with WebDriverWait.

driver.findElement(By.xpath("//button[contains(.,'Member Login')]")).click();
WebDriverWait wait = new WebDriverWait(driver, 5); // create a WebDriverWait that we will reuse
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(.,'Login to Selenium Account')]"))).click();
wait.until(ExpectedConditions.presenceOfElementLocated("email"))).sendKeys("Some Email ID");
driver.findElement("login-password")).sendKeys("Some Password");