我知道當 DOM 樹發生變化時會引發例外,解決方案是在重繪 后再次查找元素,但是......
我正在執行以下操作:
sessionsView.filterSession(sessionName);
lockSession();
approveSession();
completeSession();
在執行開始時,此代碼completeButton被禁用,如下所示:
<button _ngcontent-mfo-c209="" style="margin-right: 10px;" disabled="">Complete</button>
鎖定和批準操作由其余 API 服務完成。批準完成按鈕后啟用,所以我在重繪 后尋找它,然后嘗試單擊它。
public void completeSession() {
By completeButtonByXpath = By.xpath("*//button[text()='Complete']");
WebElement completeButton = driver.findElement(completeButtonByXpath);
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(completeButton));
completeButton.click();
}
但我收到
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
當我點擊completeButton
我也嘗試過這樣的等待
wait.until(not(ExpectedConditions.attributeContains(completeButtonByXpath, "disabled", "")));,但沒有幫助。
有什么解決辦法嗎?
uj5u.com熱心網友回復:
當你在做
driver.findElement(completeButtonByXpath);
那么此時 selenium 正在尋找*//button[text()='Complete']xPath。
并且大概在這個時候,它并不執著于HTML-DOM引起staleness。
解決方案:
一個非常簡單的解決方案是像這樣放置硬編碼的睡眠:
Thread.sleep(5000);
現在尋找WebElement completeButton = driver.findElement(completeButtonByXpath);
修改
completeSession為只有顯式等待。public void completeSession() { By completeButtonByXpath = By.xpath("*//button[text()='Complete']"); //WebElement completeButton = driver.findElement(completeButtonByXpath); WebDriverWait wait = new WebDriverWait(driver, 30); wait.until(ExpectedConditions.elementToBeClickable(completeButtonByXpath)).click(); }重試
clicking。
代碼:
public void completeSession() {
By completeButtonByXpath = By.xpath("*//button[text()='Complete']");
WebElement completeButton = driver.findElement(completeButtonByXpath);
int attempts = 0;
while(attempts < 5) {
try {
completeButton.click();
break;
}
catch(StaleElementReferenceException staleException) {
staleException.printStackTrace();
}
attempts ;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/460052.html
上一篇:Selenium在C#中呼叫異步JavaScript
下一篇:試圖突出條件格式的價值
