2015-05-09 114 views
6

所以我有這個按鈕我想點擊,如果這是你第一次點擊它。將出現一個JavaScript警報彈出窗口。我一直在使用螢火蟲,只是找不到在哪裏JavaScript是位於和我已經試過如何使用python處理selenium中的javascript警報

if EC.alert_is_present: 
     driver.switch_to_alert().accept() 
else: 
    print("no alert") 

上面的代碼工作,如果有一個警告框,但如果沒有將拋出一個錯誤。即使有一個else語句我甚至試過

if EC.alert_is_present: 
      driver.switch_to_alert().accept() 
    elif not EC.alert_is_present: 
       print("no alert") 

它拋出我這個錯誤

selenium.common.exceptions.NoAlertPresentException: Message: No alert is present 

我們怎麼解決這個得到什麼?

+0

這可能是根本原因嗎?繞過調用fxdriver.modals.clearFlag_ ... cf. https://stackoverflow.com/questions/44568402/how-do-i-manually-mouse-dismiss-a-javascript-alert-and-get-back-the-the-body-o/44592827#44592827 – NevilleDNZ

回答

8

使用嘗試捕捉如果報警不存在捕獲NoAlertPresentException例外:

from selenium.common.exceptions import NoAlertPresentException 

try: 
    driver.switch_to_alert().accept() 
except NoAlertPresentException as e: 
    print("no alert") 
+0

name' NoAlertPresentException'未定義。這是輸出。我們如何定義它? –

+0

什麼是堆棧跟蹤? – Saifur

+0

嘗試'selenium.common.exceptions.NoAlertPresentException',而不是'NoAlertPresentException' – Saifur

4

這是你如何做到這一點:

from selenium.common.exceptions import NoAlertPresentException 
try: 
    context.driver.switch_to.alert.accept() 
except NoAlertPresentException: 
    pass 

您可以用print聲明,如果你想更換pass 。請注意使用switch_to.alert而不是switch_to_alert()。後者已被棄用一段時間。在我在這裏的硒版本中,我在代碼中看到了這一點:

warnings.warn("use driver.switch_to.alert instead", DeprecationWarning) 
+0

謝謝。這工作得很好:D –

+0

我可以知道爲什麼我們不應該使用'switch_to_alert()'? –

+1

@NGGVU感謝您的詢問。我編輯了我的答案。 – Louis

相關問題