machzqcq
machzqcq

Reputation: 1029

Same scenario - StaleElementReferenceException with Java, but Watir is fine

Scenario: Open website, obtain a reference to Webelement "About" , click About , navigate back and use the variable reference again -- Results in StaleElementReference Exception. This happens only with Selenium Java, however when using Watir, it works fine. Both the code snippets are posted below. Anyone got a damn clue what is going on ?

# Below Java code produces StaleElementReferenceException
    public class StaleElementException {
    public static void main(String[] args) {
    ChromeDriver driver = new ChromeDriver();
    driver.get("http://seleniumframework.com");
    WebElement about = driver.findElementByLinkText("ABOUT");
    System.out.println(about.getText());
    about.click();
    driver.navigate().back();
    System.out.println(about.getText());
    }
    }

#Below Ruby Watir Code works fine
    require 'watir-webdriver'
    @browser = Watir::Browser.new :chrome
    @browser.goto "http://seleniumframework.com"
    about = @browser.link(text: 'ABOUT')
    puts about.text
    about.click
    @browser.back
    puts about.text

Upvotes: 0

Views: 183

Answers (2)

titusfortner
titusfortner

Reputation: 4194

Watir automatically does another find element call after the refresh, which webdriver does not do, so you need to do what Saifur suggested.

Upvotes: 1

Saifur
Saifur

Reputation: 16201

I am not sure how Watir works here. But if you find an element click on it it navigates you to a different page and the DOM refreshes. You therefore going back with driver.navigate().back(); and try to use same about element to perform your action which is not valid anymore. The DOM refreshed means the reference to the element is lost and that's not a valid element anymore. What you should be doing is finding the same element again on the fly and perform your action. The complete code should look like the following:

public class StaleElementException {
        public static void main(String[] args) {
            ChromeDriver driver = new ChromeDriver();
            driver.get("http://seleniumframework.com");
            WebElement about = driver.findElementByLinkText("ABOUT");
            System.out.println(about.getText());
            about.click();
            driver.navigate().back();
            System.out.println(driver.findElementByLinkText("ABOUT").getText());
        }
    }

Note: The change in last line

Upvotes: 1

Related Questions