1、現象
在執行UI自動化測試腳本時,有時候引用一些元素對象會拋出如下異常
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。
解決方案:
使用WebDriverWait類的構造方法接受了一個WebDriver對象和一個等待最長時間(30秒)。
然后調用until方法,其中重寫了ExpectedCondition接口中的apply方法,讓其返回一個WebElement,即加載完成的元素,然后點擊。
默認情況下,WebDriverWait每500毫秒調用一次ExpectedCondition,直到有成功的返回,當然如果超過設定的值還沒有成功的返回,將拋出異常,循環五次查找。
實際上,函數里雖然最多嘗試5次,但是一般也就查詢最多3次,也再沒有報錯,比起直接用線程等待要好很多。
public Boolean isDisplay(final String xpath, final String text) { boolean result = false; int attempts = 0; while (attempts < 5) { try { attempts++; result = new WebDriverWait(driver, 30) .until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { return driver.findElement(By.xpath(xpath)).getText().contains(text); } }); return true; } catch (Exception e) { e.printStackTrace(); } } return result; }