我遇到了这种奇怪的情况。
我是第1页的第一页,其中有一个id为“abc”的元素,我使用“abc”查找webElement并获取其文本值
我点击了第1页的链接,它转到了第2页
在第2页中,还有一个id为“abc”的元素,当我尝试使用“abc”查找元素并获取其文本值时,webdriver给了我一个“陈旧的元素异常,元素不是附加到DOM等“
我谷歌转到此页面,http://docs.seleniumhq.org/exceptions/stale_element_reference.jsp。它解释说“元素所属的那个页面已被刷新,或者用户已导航到另一个页面......驱动程序无法确定替换实际上是预期的”
那么如何解决这类问题呢?从理论上讲,webdriver无法知道这些元素在两个不同的页面中。
值得注意的是,如果我在页面切换之间插入硬编码延迟(线程睡眠等),则不会出现陈旧问题。
谢谢,
答案 0 :(得分:0)
嗨,如果你想摆脱过时的元素异常
,请按照下面的说法进行操作// Case one - when you are simply calling firstPageText two time
// then before calling it on the next page please re identify it
// to get rid of stale element exception.
String firstPageText = driver.findElement(By.id("abc")).getText();
System.out.println("Text on the first page is : " + firstPageText);
driver.findElement(By.linkText("to second page ")).click();
String secondPageText = driver.findElement(By.id("abc")).getText();
System.out.println("Text on the Second page is : " + secondPageText );
如果你已经创建了一个执行上述场景的方法,那么为了避免上述错误,请为第1页制作两个单独的方法,为第2页制作一个具有单独识别策略的方法。
答案 1 :(得分:0)
陈旧元素是已从页面中删除的元素。因此,在您的情况下,您可能正在更新文档之前获取元素。 为了避免这种情况,您可以先获得元素在获取新元素之前变为陈旧:
// get the element
WebElement element = driver.findElement(By.id("abc"));
// trigger the update of the document
driver.findElement(By.id("my-button")).click();
// wait for the element to become stale
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.stalenessOf(element));
// get the new element
WebElement element = driver.findElement(By.id("abc"));