简体   繁体   中英

Selenium Webdriver - Stale element exception when clicking on multiple dropdowns in a for loop

I have written down a code where I need to automate a dropdown with 4 options available. I am using a for loop to check the value in the dropdown and after that to click on every option present in the dropdown and to validate whether the application is returning the correct result based on the selection of dropdown.

Error found: But, after clicking on one option, it is coming out from the for loop and not executing till the size of the dropdown and returning a state element exception. Here I am attaching the code:

    Select select = new Select(hp.sort());
    List<WebElement> values = select.getOptions();
    
    for (int i = 0; i < values.size(); i++) {
        
            System.out.println(values.get(i).getText());
            
            if (values.get(i).getText().equals("Name (A to Z)")) {  
                
            }
            else if (values.get(i).getText().equals("Name (Z to A)")) {
                select.selectByVisibleText(values.get(i).getText());
                driver.navigate().refresh();
            }
            else if (values.get(i).getText().equals("Price (low to high)")) {
                select.selectByVisibleText(values.get(i).getText());
            }
            else if (values.get(i).getText().equals("Price (high to low)")){
                select.selectByVisibleText(values.get(i).getText());
            }
        
    }

What is StaleElementReferenceException

In a simple words:

Selenium has client-server architecture.

When you store WebElement/List<WebElement> in some variable in the code, all the elements are some kind of references to the real elements on the server-side. And all the elements like cached .

So this references might be easily broken if the element's structure will be changed. The easiest way to reproduce this:

WebElement myButton = driver.findElement(...); // myButton keeps the reference to the page element
driver.navigate().refresh(); // page structure changed, all existing references became broken
myButton.click(); // this will throw StaleElementReferenceException

Solution

Track any page structure updates and refresh the element references explicitly.

WebElement myButton = driver.findElement(...); // element reference created
...
driver.navigate().refresh(); // page structure changed, all existing references became broken
myButton = driver.findElement(...); // refresh the reference
myButton.click();

Also see

https://developer.mozilla.org/en-US/docs/Web/WebDriver/Errors/StaleElementReference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM