Selenium - How to overcome StaleElementReferenceException in Selenium WebDriver

分享一個大牛的人工智能教程。零基礎!通俗易懂!風趣幽默!希望你也加入到人工智能的隊伍中來!請點擊http://www.captainbed.net

In this post, we see causes of Stale Element Reference Exception and how to overcome StaleElementReferenceException in Selenium WebDriver.

What is StaleElementReferenceException

Stale means old, decayed, no longer fresh. Stale Element means an old element or no longer available element. Assume there is an element that is found on a web page referenced as a WebElement in WebDriver. If the DOM changes then the WebElement goes stale. If we try to interact with an element which is staled then the StaleElementReferenceException is thrown.

Causes of Stale Element Reference Exception

A stale element reference exception is thrown in one of two cases, the first being more common than the second. The two reasons for Stale element reference are

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

We face this stale element reference exception when the element we are interacting is destroyed and then recreated again. When this happens the reference of the element in the DOM becomes stale. Hence we are not able to get the reference to the element.

How To Overcome Stale Element Reference Exception in Selenium

Here, I will show you some ways to overcome StaleElementReferenceException.

Solution 1:

You could refresh the page and try again for the same element. Assume you are trying to click on a link and getting the stale element exception. Sample code to overcome the issue:

driver.navigate().refersh();
driver.findElement(By.xpath("xpath here")).click();

Solution 2:

If an element is not attached to DOM then you could try using "try-catch block" within "for loop".

// Using for loop, it tries for 3 times. 
// If the element is located for the first time then it breaks from the for loop nad comeout of the loop
for(int i=0; i<=2;i++){
  try{
     driver.findElement(By.xpath("xpath here")).click();
     break;
  }
  catch(Exception e){
     Sysout(e.getMessage());
  }
}

Solution 3:

Wait for the element till it gets available:

wait.until(ExpectedConditions.presenceOfElementLocated(By.id("table")));

Use ExpectedConditions.refreshed to avoid StaleElementReferenceException and retrieve the element again. This method updates the element by redrawing it and we can access the referenced element.

wait.until(ExpectedConditions.refreshed(ExpectedConditions.stalenessOf("table")));

Solution 4:

We can handle Stale Element Reference Exception by using POM (Page Object Model Design Pattern). We could avoid StaleElementException using POM. In POM, we use initElements() method which loads the element but it won’t initialize elements. initElements() takes latest address. It initializes during run time when we try to perform any action on an element. This process is also known as Lazy Initialization.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章