2015-04-29 59 views
0

在我的應用程序中,當我打開頁面時,左側顯示了選項卡列表。獲取陳舊元素引用:元素未附加到頁面文檔異常

默認情況下,一個選項卡打開狀態和其他選項卡是關閉狀態,所以我期待找到打開的狀態選項卡類名稱並單擊該選項卡,它已關閉,然後必須給另一個選項卡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"); 

回答

2

我的猜測是您的選項卡是使用JavaScript創建和刪除的。 Webdriver做的是下載網頁並將其存儲在實例中。如果由於JavaScript 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; 

}

相關問題