Selenium3 Python WebDriver API源码探析(9):JavaScript原生警告框(alert)、确认框(confirm)、提示框(prompt)处理

弹窗提示概述

Selenium专门提供了用于处理JavaScript原生弹窗提示的API。

这些JavaScript原生提示包括警告框(alert)、确认框(confirm)、提示框(prompt),它们由浏览器提供限定的样式。

  • 警告框(alert)构成主要包括提示文本和确定按钮。
    在这里插入图片描述

  • 确认框(confirm)构成主要包括提示文本、确定按钮和取消按钮。
    在这里插入图片描述

  • 提示框(prompt)构成主要包括提示文本、输入框、确定按钮和取消按钮。
    在这里插入图片描述

Selenium弹窗提示API

Selenium用于处理JavaScript原生弹窗提示的API主要由selenium\webdriver\common\alert.pyselenium\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类源码如下:

扫描二维码关注公众号,回复: 12899147 查看本文章
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()

猜你喜欢

转载自blog.csdn.net/mighty13/article/details/114840637
今日推荐