简体   繁体   中英

(StaleElementException:Selenium) How do I handle this?

This is my first time first day working on selenium and I have no hands on experience on Web Technologies in depth either.

Working around, I have been facing StaleElementException while i try to access a particular object on the DOM.

Following Method handles all the task:

private void extract(WebDriver driver) {
    try {

        List<WebElement> rows = driver.findElements(By.xpath("//*[@id='gvSearchResults']/tbody/tr"));

        for (WebElement row : rows) {
            WebElement columns = row.findElement(By.xpath("./td[1]/a"));

            if (assertAndVerifyElement(By.xpath("//*[@id='gvSearchResults']/tbody/tr/td[1]/a"))) {
                columns.click();
            }

            List<WebElement> elements = driver
                    .findElements(By.xpath("//*[@id='ctl00_MainContent_pnlDetailsInd']/table/tbody/tr"));

            for (WebElement element : elements) {
                WebElement values = element.findElement(By.xpath("./td[1]"));
                System.out.print(values.getText() + " ");
                WebElement values2 = element.findElement(By.xpath("./td[2]"));
                System.out.println(values2.getText());
            }
            if(assertAndVerifyElement(By.xpath("//*[@id='ctl00_MainContent_btnBack']")))
                driver.findElement(By.xpath("//*[@id='ctl00_MainContent_btnBack']")).click();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } 
}

The Assertion logic goes here:

public boolean assertAndVerifyElement(By element) throws InterruptedException {
    boolean isPresent = false;

    for (int i = 0; i < 5; i++) {
        try {
            if (driver.findElement(element) != null) {
                isPresent = true;
                break;
            }
        } catch (Exception e) {
            // System.out.println(e.getLocalizedMessage());
            Thread.sleep(1000);
        }
    }
    Assert.assertTrue("\"" + element + "\" is not present.", isPresent);
    return isPresent;
}

I have tried few solutions asking me to use wait until expected conditions, but none of them worked.

Also, It would be appreciated if you point out any bad design practices I might be using in the above sample.

I can give you the idea to overcome staleness.

Generally we will be getting the Stale Exception if the element attributes or something is changed after initiating the webelement. For example, in some cases if user tries to click on the same element on the same page but after page refresh, gets staleelement exception.

To overcome this, we can create the fresh webelement in case if the page is changed or refreshed. Below code can give you some idea.

Example:

webElement element = driver.findElement(by.xpath("//*[@id='StackOverflow']"));
element.click();
//page is refreshed
element.click();//This will obviously throw stale exception

To overcome this, we can store the xpath in some string and use it create a fresh webelement as we go.

String xpath = "//*[@id='StackOverflow']";
driver.findElement(by.xpath(xpath)).click();
//page has been refreshed. Now create a new element and work on it
driver.findElement(by.xpath(xpath)).click();   //This works

Another example:

for(int i = 0; i<5; i++)
{
  String value = driver.findElement(by.xpath("//.....["+i+"]")).getText);
  System.out.println(value);
}

Hope this helps you. Thanks

The StaleElementException occurs when the webelement in question is changed on the dom and the initial reference to that webelement is lost.

You can search for the webelement again

try this

try:
 element = self.find_element_by_class('')
 element.click()
except StaleElementReferenceException:
 element = self.find_element_by_class('')
 element.click()

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