Sunday, July 2, 2017

How to handle StaleElementReference Exception in Selenium?

The meaning of stale is no longer fresh. And when we say stale element which means element is not fresh or not valid.

The StaleElementRefrence  exception occurs when the web driver is trying to perform an action on the element that is no longer available on the page.

This exception will be thrown between an element identification and action being performed on the element”.

WebElement element = driver.findElement("btn_id")); // The element btn_id is identified or located.

Now assume before performing an action on the above identified element, some other action has just happened on the page, say page refresh or some other click() action. Due to this DOM has changed/not loaded object properties completely or the element is removed from the page for a while. if we perform action during this period;  driver throws StaleElementReferenceException. 

To over come this problem we need to make the driver to wait till the element is re-added to the page or DOM.

In the below code snippet driver is trying to click on the element as soon as it is either changed in DOM or removed from page.

And now in the below code snippet we are using a user defined wait function waitForElement(); which will wait till the element is re-added to the DOM or page and then get identified. Clicking action is being performed successfully now.

We may use any other wait method, whatever we used is a one way of waiting for element and it is more professional way of writing wait method.


DevOps 01: What is DevOps and How it benefits organizations?

DevOps is a culture in an organization, where the development team and operations team help each other by sharing information, process and t...