1、現象
在執行腳本時,有時候引用一些元素對象會拋出如下異常
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
2、報錯原因
官方給出解釋如下:
The element has been deleted entirely.
The element is no longer attached to the DOM.
我個人理解:
就是頁面元素過期,引用的元素過時,不再依附於當前頁面,需要重新定位獲取元素對象
如果JavaScript把網頁給刷新了,那麼操作的時候就會碰到Stale Element Reference Exception。
官方地址:http://docs.seleniumhq.org/exceptions/stale_element_reference.jsp
解決方案:
使用WebDriverWait類的構造方法接受了一個WebDriver對象和一個等待最長時間(30秒)。然後調用until方法,其中重寫了ExpectedCondition接口中的apply方法,讓其返回一個WebElement,即加載完成的元素,然後點擊。默認情況下,WebDriverWait每500毫秒調用一次ExpectedCondition,直到有成功的返回,當然如果超過設定的值還沒有成功的返回,將拋出異常,循環五次查找,實際實驗發現,函數裏雖然最多嘗試5次,但是一般也就查詢最多3次,也在沒有報錯,比起線程等待要好很多,
代碼如下:
/**
* 等待指定元素文本出現
*
* @param xpath
* @param text
* @return
* @throws Exception
*/
public Boolean isDisplay(final String xpath, final String text) {
logger.info("等待指定元素文本顯示");
boolean result = false;
int attempts = 0;
while (attempts < 5) {
try {
attempts++;
logger.info("掃描開始元素開始第" + attempts + "次");
result = new WebDriverWait(driver, 30)
.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return driver.findElement(By.xpath(xpath)).getText().contains(text);
}
});
logger.info("掃描開始元素結束");
return true;
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}