5

I have a div with a unique ID. Under that div are a bunch of span elements that have className=foo. There are several span elements with className=foo but they are unique to each div (if that's clear). So my Selenium code first gets the unique div as a web element then tries to take that element and get by class name the span like so

element = sDriver.findElement(By.id("c_"+cID)); 
String sTest = element.findElement(By.className("actions")).getText();

On the second line it throws an exception every time

org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
Command duration or timeout: 22 milliseconds

Do I misunderstand how to get that span from under a unique div?

shamp00
  • 11,106
  • 4
  • 38
  • 81
ducati1212
  • 855
  • 9
  • 18
  • 29

2 Answers2

7

Nope you'right accessing the span but the problem is that the Dom has changed since StaleReferenceException is about (see StaleReferenceException )

This may be caused because the page isn't loaded completely when the code starts or changes when the code is executed. You can either try to wait a little longer for the element or catch the StaleReferenceException and try again finding the div and the span.

chaosr
  • 494
  • 2
  • 6
  • 17
  • You can also check here for [a possible solution](http://stackoverflow.com/a/7474518/1077279). – shamp00 Jan 12 '12 at 15:06
  • This seems to be it if I put in a sleep and wait a few seconds it works fine. With no good way to tell if the page has fully loaded I think unfortunately I need to just use a sleep – ducati1212 Jan 12 '12 at 16:01
  • you may combine both a sleep and catching the exception. Try access both elements without sleep in the first place and when it fails use a sleep and try again afterwards – chaosr Jan 12 '12 at 19:55
  • Works fine with catching the exception. I have a getText() and a click(). It throws the exception at getText() though it can further click. I caught the exception since nothing was wrong with my code. – Michiru Nov 11 '13 at 14:17
1

My solution is not fancy but it works like a Swiss watch (in my situation of course). So my code is calling the parent element in a loop looking for different child elements in it. Nothing got changed at all - just simple querying and the exception began to occur. So! I've added the Thread.Sleep(2000) command before every search of parent element and it solver the problem. Not elegant but works every time with minimum code to debug afterwards.