How to handle StaleElementReferenceException

I have a scenario where I am attempting to loop through  a number of elements on a bar chart, until I find the “rect” tag name. When I click on the “rect” tag name, the individual bar is selected from the chart, and I am redirect to another page. Please see below for an image of the bar chart I am working with:
http://imgur.com/xU63X1Z

For reference, the bar chart  I am working with is the top right-hand side. The test I want to execute is to click on the first bar in the chart; doing so, will redirect me to an appropriate page. In order to do this I have written the following code in Selenium Webdriver using Eclipse (Java)


WebElement deliveredChartDailyFocus = driver.findElement(By.id("delivered-chart-daily"));

deliveredChartDailyFocus.click();
List<WebElement> children = deliveredChartDailyFocus.findElements(By.tagName("rect"));

Iterator<WebElement> iter = children.iterator();
while (iter.hasNext()) {

WebElement we = iter.next();
if(we.isDisplayed()){

we.click();

}

Everything appears to work well in that the above code hits the “rect” element and redirects me to the appropriate page. However, when I hit the page I then get an error as the code is still looking for the “rect” value which isn’t on the new page.

You’ll notice that there is a “break” line missing from the above…..this is because, upon debugging the code I found that when iterating through the loop, the click event does not kick in until the 3rd iteration, I’m assuming because the “rect” element is not visible? Therefore, if I put in a “break” statement it exits out of the loop after the first iteration, and therefore I never get to the part where I carry out the “click” event to navigate to the new page.

Essentially, what I’m after is a way of being able to loop as many times as necessary until the appropriate “rect” element can be located. Upon clicking on that, I am redirected to the new page….only at that point do I want the loop to exit, so that the “NoSuchElementException error is not displayed.

If any more details are required please let me know, would really appreciate any guidance on this.

tilston1001 Train Asked on January 28, 2015 in Selenium WebDriver.
Add Comment
0 Answer(s)

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.