user3561614
user3561614

Reputation: 1094

handle refreshing WebElement with Selenium

I'm testing a Website consisting of multiple frames. The server can regenerate a frame at any time, even if no element changed. If this happens during

driver.findElement(By.id("11")).getText();

between findElement and getText, a StaleElementExcpetion is thrown. My current solution is to retry multiple times.

for (int i = 0; i < 3; i++) {
    try {
        driver.findElement(By.id("11")).getText();

    } catch (StaleElementException e) {
        // retry
    }    
}

This realy bloats the code, any better solution?

Upvotes: 1

Views: 3469

Answers (2)

Raja Gopal
Raja Gopal

Reputation: 44

First we have to identify in which frame your gettext is present, then switch to the particular frame and then find for the element.

Syntax:

   driver.switchTo().frame("frameName"); //name of the frame
   driver.switchTo().frame(1); //index

Example:

     driver.switchTo().frame(1);
     driver.findElement(By.xpath("//p")).getText();
     driver.switchTo().defaultContent();

Note:

     driver.switchTo().defaultContent(); //Used default frame, I.E. If there are three frames in one page named as 1,2,3. If you want to switch from frame 2 to frame 3, In that case we are not able to switch directly to the frame 3, In this case what we have to do is 
     driver.switchTo().frame("2"); //frame 2
     driver.switchTo().defaultContent();// main window - (Default page) while loading webpage
     driver.switchTo().frame("3"); //frame 3

Please find the following path for the reason: StaleElementException

  1. The element has been deleted entirely.
  2. The element is no longer attached to the DOM

http://www.seleniumhq.org/exceptions/stale_element_reference.jsp

Upvotes: 0

StefanE
StefanE

Reputation: 7630

Write a function that does that for you to make the code look less bloated but I don't believe there a better way to solve this problem.

A good blog article here: StaleElementException

Upvotes: 2

Related Questions