0

I'm using the PageObject/PageFactory design pattern for my UI automation. Using Selenium 2.0 WebDriver, JAVA, I randomly get the error: org.openqa.selenium.StaleElementReferenceException: Element is no longer attached to the DOM, when I attempt logic like this:

@FindBy(how = HOW.ID, using = "item")
private List<WebElement> items

private void getItemThroughName(String name) {
    wait(items);

    for(int i = 0; i < items.size(); i++) {
        try {
            Thread.sleep(0500);
        } catch (InterruptedException e) { }

        this.wait(items);
        if(items.get(i).getText().contains(name)) {
            System.out.println("Found");
            break;
        }
    }
}

The error randomly happens at the if statement line, as you can see I've tried a couple things to avoid this, like sleeping a small amount of time, or waiting for the element again, neither works 100% of the time

3
  • Do you have any JavaScript on your web page that might remove items from the page? Commented Aug 31, 2012 at 19:08
  • Have you tried using the actual Explicit Wait methods in Selenium? This error is usually a race condition issue. Commented Aug 31, 2012 at 21:40
  • Just like Arran said: try using waits from webdriver. Using Thread.sleep() is a bad practice and should be avoided. You may never know whether the 500ms interval is enough or not and thus random errors appear. Try implicit/explicit waits or even go further by using FluentWait class Commented Sep 3, 2012 at 9:58

1 Answer 1

1

First if you really have multiple elements on the by with the ID of "item" you should log a bug or talk to the developers on the site to fix that. An ID is meant to be unique.

As comments on the question already implied you should use an ExplicitWait in this case:

private void getItemThroughName(String name) {
    new WebDriverWait(driver, 30)
               .until(ExpectedConditions.presenceOfElementLocated(
                 By.xpath("id('item')[.='" + name + "']")
               ));
    // A timeout exception will be thrown otherwise
    System.out.println("Found");
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.