Java 获取过时元素引用:元素未附加到页面文档异常

Java 获取过时元素引用:元素未附加到页面文档异常,java,selenium,Java,Selenium,在我的应用程序中,当我打开页面时,左侧显示选项卡列表 默认情况下,一个选项卡为打开状态,其他选项卡为关闭状态,因此我正在查找打开的状态选项卡类名,并单击该选项卡,它已关闭,然后必须为另一个选项卡提供打开id 在执行代码时,我得到了“stale-element-reference:元素未附加到页面文档”异常 我也尝试过隐式等待选项 请任何人帮助解决这个问题好吗 driver.manage().timeouts().implicitlyWait(1000,TimeUnit.SECONDS);

在我的应用程序中,当我打开页面时,左侧显示选项卡列表

默认情况下,一个选项卡为打开状态,其他选项卡为关闭状态,因此我正在查找打开的状态选项卡类名,并单击该选项卡,它已关闭,然后必须为另一个选项卡提供打开id

在执行代码时,我得到了“stale-element-reference:元素未附加到页面文档”异常

我也尝试过隐式等待选项

请任何人帮助解决这个问题好吗

driver.manage().timeouts().implicitlyWait(1000,TimeUnit.SECONDS);

                  WebElement element5 = driver.findElement(By.className("TopItemActive"));
                  if(element5.isEnabled())
                  {
                  element5.click();
                  }

                  driver.manage().timeouts().implicitlyWait(2000,TimeUnit.SECONDS);
                WebElement element6 = driver.findElement(By.id("id_16_cell"));        
                element6.click();
                System.out.println("Tab opened");

我猜你的标签是用JavaScript创建和删除的。Webdriver所做的是下载网页并将其存储在实例中。如果由于javascript而更改了某些内容,webdriver并不总是知道

这可以作为一个简单的解决方案

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.refreshed(ExpectedConditions.elementToBeClickable(by)));
我发现这件事没什么可做的。我捕获抛出的异常并重试。所以我为“点击”创建了一个新函数

公共字符串单击(按){
字符串文本=”;
driver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
布尔未找到=真;
int=0;
while(未找到并尝试<3){
尝试次数+=1;
试一试{
wait.until(ExpectedConditions.refreshed(ExpectedConditions.visibilityOfElementLocated(by));
text=driver.findElement(by).click();
未找到=错误;
logger.info(“单击元素”+stribby(按));
}捕获(StaleElementReferenceException-ser){
error(“error:Stale元素异常。”+stribby(by));
}捕获(非接触元素异常nse){
logger.error(“错误:无此类元素异常。”+stribby(by)+“\n错误:+nse);
}捕获(例外e){
logger.error(例如getMessage());
}
}
如果(未找到)
Assert.assertTrue(false,“未能通过定位器”+stripBy(by))定位元素);
返回文本;
}

public String click(By by){

   String text = "";

   driver.manage().timeouts().implicitlyWait( 5, TimeUnit.SECONDS );
   boolean unfound = true;
   int tries = 0;
   while ( unfound && tries < 3 ) {
     tries += 1;
     try {
       wait.until(ExpectedConditions.refreshed(ExpectedConditions.visibilityOfElementLocated(by)));
       text = driver.findElement(by).click();
       unfound = false;
       logger.info("Click element "+stripBy(by));
     } catch ( StaleElementReferenceException ser ) {
       logger.error( "ERROR: Stale element exception. " + stripBy(by) );
     } catch ( NoSuchElementException nse ) {
       logger.error( "ERROR: No such element exception. " + stripBy(by)+"\nError: "+nse );
     } catch ( Exception e ) {
       logger.error( e.getMessage() );
     }
   }

   if(unfound)
   Assert.assertTrue(false,"Failed to locate element by locator " + stripBy(by));

   return text;