Python

Python 中有多種方法可以切換到警報彈出視窗:

  1. 不推薦
alert = driver.switch_to_alert()
  1. 使用 switch_to
alert = driver.switch_to.alert
  1. 使用 ExplicitWait
 from selenium.webdriver.common.by import By
 from selenium.webdriver.support.ui import WebDriverWait
 from selenium.webdriver.support import expected_conditions as EC

 alert = WebDriverWait(driver, TIMEOUT_IN_SECONDS).until(EC.alert_is_present())
  1. 通過宣告 Alert 類的例項
from selenium.webdriver.common.alert import Alert

alert = Alert(driver)

要填充由 JavaScript prompt() 觸發的彈出視窗中的輸入欄位:

alert.send_keys('Some text to send')

確認對話方塊彈出*:

alert.accept()

解僱:

alert.dismiss()

要從彈出視窗獲取文字:

alert.text

* PS alert.dismiss() 可用於確認由 JavaScript alert() 以及 alert.confirm() 觸發的彈出視窗