我有一个带有唯一 ID 的 div
。在该 div
下是一堆具有 className=foo
的 span
元素。有多个带有 className=foo
的 span
元素,但它们对于每个 div
都是唯一的(如果清楚的话)。因此,我的 Selenium 代码首先获取唯一的 div
作为 Web 元素,然后尝试获取该元素并通过类名获取 span
,如下所示
element = sDriver.findElement(By.id("c_"+cID));
String sTest = element.findElement(By.className("actions")).getText();
第二行每次都会抛出异常
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
我是否误解了如何从唯一的 div
下获取该 span
?
最佳答案
不,你正确地访问了跨度,但问题是自从 StaleReferenceException 发生以来 Dom 已经改变了(参见 StaleReferenceException )
这可能是因为代码启动时页面未完全加载或者代码执行时页面发生变化导致的。您可以尝试等待元素更长的时间,或者捕获 StaleReferenceException 并再次尝试查找 div 和 span。
关于Selenium WebDriver 访问子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8836712/