Selenium WebDriver访问子元素

duc*_*212 5 selenium webdriver selenium-webdriver

我有一个div唯一的ID.在那之下div有一堆span元素className=foo.有几个span元素,className=foo但每个元素都是独一无二的div(如果清楚的话).所以,我的硒代码首先获取独特div的网络元素,然后尝试采取元素和类的名称得到span像这样

element = sDriver.findElement(By.id("c_"+cID)); 
String sTest = element.findElement(By.className("actions")).getText();
Run Code Online (Sandbox Code Playgroud)

在第二行,它每次都抛出一个异常

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
Run Code Online (Sandbox Code Playgroud)

我是否误解了如何span从一个独特的东西中获得它div

cha*_*osr 7

你没有访问该范围,但问题是自StaleReferenceException以来Dom已经发生了变化(参见StaleReferenceException)

这可能是由于在代码启动时未完全加载页面或在执行代码时更改页面而引起的.您可以尝试等待元素一段时间或捕获StaleReferenceException并再次尝试查找div和span.