How to avoid “StaleElementReferenceException” in Selenium?

前端 未结 16 2078
一向
一向 2020-11-22 12:12

I\'m implementing a lot of Selenium tests using Java. Sometimes, my tests fail due to a StaleElementReferenceException. Could you suggest some approaches to mak

16条回答
  •  有刺的猬
    2020-11-22 12:55

    I've found solution here. In my case element becomes inaccessible in case of leaving current window, tab or page and coming back again.

    .ignoring(StaleElement...), .refreshed(...) and elementToBeClicable(...) did not help and I was getting exception on act.doubleClick(element).build().perform(); string.

    Using function in my main test class:

    openForm(someXpath);
    

    My BaseTest function:

    int defaultTime = 15;
    
    boolean openForm(String myXpath) throws Exception {
        int count = 0;
        boolean clicked = false;
        while (count < 4 || !clicked) {
            try {
                WebElement element = getWebElClickable(myXpath,defaultTime);
                act.doubleClick(element).build().perform();
                clicked = true;
                print("Element have been clicked!");
                break;
            } catch (StaleElementReferenceException sere) {
                sere.toString();
                print("Trying to recover from: "+sere.getMessage());
                count=count+1;
            }
        }
    

    My BaseClass function:

    protected WebElement getWebElClickable(String xpath, int waitSeconds) {
            wait = new WebDriverWait(driver, waitSeconds);
            return wait.ignoring(StaleElementReferenceException.class).until(
                    ExpectedConditions.refreshed(ExpectedConditions.elementToBeClickable(By.xpath(xpath))));
        }
    

提交回复
热议问题