0
public class ClearSearch {

    public static void main(String[] args) throws InterruptedException {
        //Step 1:
        ChromeDriver driver = new ChromeDriver();
        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(15));
        WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(15)); 
        driver.manage().window().maximize();
                
        //Step 2: Hit URL
        driver.get("https://rahulshettyacademy.com/seleniumPractise/#/");
                
        List<WebElement> products = driver.findElements(By.xpath("//div[@class='products-wrapper']//h4"));
        products.stream().forEach(p-> System.out.println(p.getText()));
        System.out.println();
                
        driver.findElement(By.cssSelector(".search-keyword")).sendKeys("Beet",Keys.ENTER);
        Thread.sleep(Duration.ofSeconds(1));
            
        driver.findElement(By.cssSelector(".search-keyword")).sendKeys(Keys.BACK_SPACE);
        driver.findElement(By.cssSelector(".search-keyword")).sendKeys(Keys.BACK_SPACE);
        products = driver.findElements(By.xpath("//div[@class='products-wrapper']//h4"));
        products.stream().forEach(p-> System.out.println(p.getText()));
        boolean match = products.stream().anyMatch(p->p.getText().contains("Be"));
        Assert.assertTrue(match);
    }
}

The execution is so quick its giving a stale element exception. But when Thread.sleep is added the error is gone. I have tried explicit wait for visibility of elements and it is not working. How to avoid Thread.Sleep()

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95

2 Answers2

0

A stale element exception is thrown by selenium, when a reference you had to an element is destroyed and recreated, making the reference "stale". You just need to refresh the reference (so, re-get it) before doing anything with it, to make sure it's not stale.

0x150
  • 589
  • 2
  • 11
0

StaleElementReferenceException is happened, because entity you're trying to get is not exist anymore.

In your case, after clicking backspace button you're getting new list, when actually old one is shown. After few moments new one is shown, but your collection has references to old one.

One of the solutions is to wait until old collection is not exist anymore after clicking backspace.

     WebDriverWait wdwait = new WebDriverWait(driver, 10);
     List<WebElement> products = driver.findElements(By.xpath("//div[@class='products-wrapper']//h4"));
     products.stream().forEach(p-> System.out.println(p.getText()));

     driver.findElement(By.cssSelector(".search-keyword")).sendKeys("Beet",Keys.ENTER);

     driver.findElement(By.cssSelector(".search-keyword")).sendKeys(Keys.BACK_SPACE);
     driver.findElement(By.cssSelector(".search-keyword")).sendKeys(Keys.BACK_SPACE);
     wdwait.until(ExpectedConditions.stalenessOf(products.get(0)));
     // your other code
``
Yaroslavm
  • 1,762
  • 2
  • 7
  • 15