弹窗提示概述
Selenium
专门提供了用于处理JavaScript原生弹窗提示的API。
这些JavaScript原生提示包括警告框(alert)、确认框(confirm)、提示框(prompt),它们由浏览器提供限定的样式。
-
警告框(alert)构成主要包括提示文本和确定按钮。
-
确认框(confirm)构成主要包括提示文本、确定按钮和取消按钮。
-
提示框(prompt)构成主要包括提示文本、输入框、确定按钮和取消按钮。
Selenium
弹窗提示API
Selenium
用于处理JavaScript原生弹窗提示的API主要由selenium\webdriver\common\alert.py
和selenium\webdriver\remote\switch_to.py
实现。
Alert
类
selenium\webdriver\common\alert.py
中的Alert
类是API的主要实现。
类签名:class Alert(driver)
主要提供了一个特性和三个方法。
text
特性:获取提示文本。accept
方法:点击确定按钮。dismiss
方法:点击取消按钮。send_keys
方法:向提示框(prompt)中的输入框输入文本。
利用switch_to
对象实现Alert
类的实例化
除了传统的Alert(driver)
的类实例化方式之外,selenium\webdriver\remote\switch_to.py
也提供了一种实例化方式。即driver.switch_to.alert
。
根据selenium\webdriver\remote\switch_to.py
源码可知。
@property
def alert(self):
"""
Switches focus to an alert on the page.
:Usage:
alert = driver.switch_to.alert
"""
alert = Alert(self._driver)
alert.text
return alert
利用期望条件实现Alert
类的实例化
Selenium
内置了一系列异常类,这些类定义在selenium\webdriver\support\expected_conditions.py
中。其中alert_is_present
类就是与弹窗提示相关的异常类,结合《Selenium3 Python WebDriver API源码探析(8):等待(显式等待、隐式等待)、超时(页面加载超时、异步脚本调用超时)》中的显示等待方法,可实现动态检测弹窗提示。代码示例如下:
alert = WebDriverWait(driver, 5).until(expected_conditions.alert_is_present())
alert_is_present
类源码如下:
class alert_is_present(object):
""" Expect an alert to be present."""
def __init__(self):
pass
def __call__(self, driver):
try:
alert = driver.switch_to.alert
return alert
except NoAlertPresentException:
return False
Selenium
弹窗提示处理案例
import time
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
driver = webdriver.Firefox()
# 模拟弹出警告框
driver.execute_script("alert(123)")
alert = WebDriverWait(driver, 3).until(expected_conditions.alert_is_present())
print(alert.text)
time.sleep(3)
# 点击确定
alert.accept()
# 模拟弹出确认框
driver.execute_script("confirm(456)")
alert2 = WebDriverWait(driver, 3).until(expected_conditions.alert_is_present())
print(alert2.text)
time.sleep(3)
# 点击取消
alert2.dismiss()
# 模拟弹出prompt框
driver.execute_script("prompt(678)")
WebDriverWait(driver, 3).until(expected_conditions.alert_is_present())
alert3 = driver.switch_to.alert
alert3.send_keys("Willian Shakesphere")
print(alert3.text)
time.sleep(5)
alert3.accept()