Home > Software design >  Adding a Thread.sleep in my Selenium scripts is breaking the execution
Adding a Thread.sleep in my Selenium scripts is breaking the execution

Time:01-03

It's a simple Selenium script where I am launching a URL and performing a couple of Click actions. When I put a Thread.sleep(2000) between any of these few steps, execution breaks and I get an exception as shown below.

Dec 26, 2022 3:55:35 PM org.openqa.selenium.support.ui.ExpectedConditions findElement WARNING: WebDriverException thrown by findElement(By.xpath: //button[text()='Continue']) org.openqa.selenium.NoSuchWindowException: no such window: target window already closed from unknown error: web view not found

If I remove the Thread.sleep step, Its proceeding forward. Can someone help me understand why is Thread.sleep causing this issue and how to resolve this ?

Below is the code:

    WebDriverManager.chromedriver().setup();
    ChromeOptions options = new ChromeOptions();
    options.addArguments("start-maximized");
    options.addArguments("enable-automation");
    options.addArguments("--no-sandbox");
    options.addArguments("--disable-infobars");
    options.addArguments("--disable-dev-shm-usage");
    options.addArguments("--disable-browser-side-navigation");
    options.addArguments("--disable-gpu");
    driver = new ChromeDriver(options);
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    wait = new WebDriverWait(driver, 30)
    
    driver.get("<ApplicationURL>");
    Thread.sleep(2000);
    driver.findElement(By.xpath("<some button to click>")).click();

Observation: This issue is occurring when trying CHROME browser only and that too on MAC alone. On Windows, this works fine. FYI, Chrome browser version: 108.0.5359.124 ChromeDriver version: 108.0.5359.71 MAC OS version : Monterey 12.6.2 Java version : 1.8.0_352 Selenium version : 3.11.0

CodePudding user response:

Adding a throws declaration for InterruptedException is necessary. If that is already added, then the error could be caused by the flow of the script. Depending on the wait for 2 seconds, the element may not be available.

CodePudding user response:

It may be happing but it we have implicit wait and explicit wait.. Lets use explicit wait instead of thread.sleep.

WebDriverWait wait = new WebDriverWait(driver, 30);
driver.get("<ApplicationURL>");
WebElement element = driver.findElement(By.xpath("<some button to click>"));
wait..until(ExpectedConditions.visibilityOf(element));
element.click();
  • Related