【问题标题】:Getting stale element reference: element is not attached to the page document exception获取过时的元素引用:元素未附加到页面文档异常
【发布时间】:2015-04-29 10:35:39
【问题描述】:

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

默认情况下,一个选项卡处于打开状态,其他选项卡处于关闭状态,所以我正在寻找打开的状态选项卡类名称并单击选项卡,它已关闭,然后必须提供另一个选项卡 ID 才能打开。

在执行代码时,我收到 “过时的元素引用:元素未附加到页面文档” 异常。

我也尝试过隐式等待选项。

有人可以帮忙解决这个问题吗?

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");

【问题讨论】:

    标签: java selenium


    【解决方案1】:

    我的猜测是您的标签是使用 JavaScript 创建和删除的。 Webdriver 所做的是下载网页并将其存储在实例中。如果由于 javascript webdriver 发生了某些变化,webdriver 并不总是意识到这一点。

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

    WebDriverWait wait = new WebDriverWait(driver, 10);
    wait.until(ExpectedConditions.refreshed(ExpectedConditions.elementToBeClickable(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;
    

    }

    【讨论】:

      猜你喜欢
      • 2021-12-15
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多