selenium alert/popup window
Command
- alert = browser.switch_to_alert()
取得對話框物件
- alert = browser.switch_to.alert
取得對話框物件
- alert.accept()
按下 OK 按鈕
- alert.dismiss()
按下 Cancel 按鈕
- alert.text
取得對話框文字
- from selenium.webdriver.support import expected_conditions
expected_conditions.alert_is_present()(browser)
用來檢測是否有 alert 視窗
Demo
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
browser = webdriver.Firefox()
browser.get("url")
browser.find_element_by_id("button").click()
try:
WebDriverWait(browser, 3).until(EC.alert_is_present())
alert = browser.switch_to.alert
alert.accept()
print("alert accepted")
except TimeoutException:
print("no alert")
Reference
- alert = browser.switch_to_alert()
取得對話框物件 - alert = browser.switch_to.alert
取得對話框物件 - alert.accept()
按下 OK 按鈕 - alert.dismiss()
按下 Cancel 按鈕 - alert.text
取得對話框文字 - from selenium.webdriver.support import expected_conditions
expected_conditions.alert_is_present()(browser)
用來檢測是否有 alert 視窗
Demo
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
browser = webdriver.Firefox()
browser.get("url")
browser.find_element_by_id("button").click()
try:
WebDriverWait(browser, 3).until(EC.alert_is_present())
alert = browser.switch_to.alert
alert.accept()
print("alert accepted")
except TimeoutException:
print("no alert")
Reference
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException browser = webdriver.Firefox() browser.get("url") browser.find_element_by_id("button").click() try: WebDriverWait(browser, 3).until(EC.alert_is_present()) alert = browser.switch_to.alert alert.accept() print("alert accepted") except TimeoutException: print("no alert")
留言
張貼留言