2013-07-19 44 views
3

我想用Selenium WebDriver處理對話框(確定取消類型)。所以我的目標是點擊「確定」按鈕。Selenium NoAlertPresentException

的情況是:

  1. 用於調用點擊按鈕對話框

    button.click();

  2. 嘗試接受

    webDriver.switchTo().alert().accept();

但我總是得到NoAlertPresentException並且幾乎立即看到對話框關閉。 在我看來,Selenium自動關閉對話框,當我想接受時,沒有什麼可以接受的。

對不起我的英文不好。

+1

它是一個時機的問題? –

+0

你在使用哪個驅動程序?例如,SafariDriver會自動關閉所有警報,因爲它無法處理它們。 – Ardesco

+0

你有沒有解決這個問題?我有完全相同的問題。並沒有任何Google考古學似乎幫助:) – rohdester

回答

4

這個問題的原因一般是硒是太快,試圖接受尚未通過瀏覽器中打開警報。這可以簡單地通過固定的明確的等待:

button.click(); 
WebDriverWait wait = new WebDriverWait(driver, 5); 
Alert alert = wait.until(ExpectedConditions.alertIsPresent()); 
alert.accept(); 
0
public boolean isAlertPresent(){ 
    try{ 
     Alert a = new WebDriverWait(driver, 10).until(ExpectedConditions.alertIsPresent()); 
     if(a!=null){ 
      System.out.println("Alert is present"); 
      driver.switchTo().alert().accept(); 
      return true; 
     }else{ 
      throw new Throwable(); 
     } 
    } 
    catch (Throwable e) { 
     System.err.println("Alert isn't present!!"); 
     return false; 
    } 

} 

使用明確的等待檢查警報,然後做了手術。這可能會幫助你。 :)

0

一般來說,是因爲Selenium命令運行太快並嘗試關閉該警告之前,它是開放的。因此,在點擊事件之後添加延遲應該可以解決問題。另外,如果您正在使用Safari瀏覽器進行測試,那麼SafariDriver在處理警報時會遇到一些問題。 SafariDriver cannot handle alerts應該爲您提供更多的細節。

1
Step 1: 
    public boolean isAlertPresent(){ 
      boolean foundAlert = false; 
      WebDriverWait wait = new WebDriverWait(driver, 0 /*timeout in seconds*/); 
      try { 
       wait.until(ExpectedConditions.alertIsPresent()); 
       foundAlert = true; 
       System.out.println("isAlertPresent : " +foundAlert); 
      } catch (TimeoutException eTO) { 
       foundAlert = false; 
       System.out.println("isAlertPresent : " +foundAlert); 
      } 
      return foundAlert; 
     } 

Step 2: 
public boolean tocheck_POP_Dialog() 
    { Alert alert; 
     try 
     { 
      alert=driver.switchTo().alert(); 


     } 
     catch(NoSuchElementException elementException) 
     { 
      return false; 
     } 

     alert.accept(); //Close Alert popup 


     return true; 
    } 




Step 3 : 
if(dummyPage.isAlertPresent()) 
       { 
        dummyPage.tocheck_POP_Dialog(); 
       } 
+0

雖然此代碼段可能會解決問題,但[包括解釋](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 –

+1

第一個函數返回是否有警報。 –

+1

第二個功能點擊警報確定按鈕 –