ducati1212
ducati1212

Reputation: 855

Selenium WebDriver access a sub element

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?

Upvotes: 5

Views: 11044

Answers (2)

user1922804
user1922804

Reputation: 19

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.

Upvotes: 1

chaosr
chaosr

Reputation: 494

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.

Upvotes: 7

Related Questions