[英]How to handle intermittent alert in Selenium WebDriver?
我有自動化場景,有時系統返回javascript警報,有時根本不返回。 我不知道是什么原因,可能是網絡問題。 我已經為此創建了警報處理程序:
public boolean isAlertPresent() {
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.alertIsPresent());
return true;
}
我在我的一個步驟中稱之為有時出現警報:
public WSSPage enterAndSearchContent(String title) throws InterruptedException {
waitForElementTextWithEnter(searchTextField, title);
while (isAlertPresent()){
Alert alert = driver.switchTo().alert();
alert.dismiss();
break;
}
return PageFactory.initElements(driver, WSSPage.class);
}
問題是當警報沒有顯示時,它會給我NoAlertPresentException,並且自動化結果將失敗。 如果通過移動到下一行沒有發生警報,我希望代碼繼續前進,在這種情況下,它將只返回PageFactory.initElements(driver, WSSPage.class);
你能幫我提供更好的代碼嗎? 非常感謝。
JavascriptExecutor為你工作。 在單擊調用警報的事件之前,請務必執行它。
((JavascriptExecutor) driver).executeScript("window.confirm = function(msg) { return true; }");
注意: - 點擊調用警報確認框的事件后不要使用它。 默認情況下,上面的代碼將確認框設置為true表示如果調用,則表示您接受/單擊該頁面上所有確認框中的確定
希望它能幫到你:)
您可以修改方法isAlertPresent,如下所示並嘗試。 它可能會幫助你。
public boolean isAlertPresent() {
try{
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.alertIsPresent());
return true;
}
catch (NoAlertPresentException noAlert) {
return false;
}
catch (TimeoutException timeOutEx){
return false;
}
}
您可以在try catch中包含該特定異常。 然后將捕獲異常,並且不會通過任何錯誤,您的執行將繼續。 還可以使用較少的時間戳創建隱式等待來處理此問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.