• Selenium2+python自动化47-判断弹出框存在(alert_is_present)【转载】


    前言

    系统弹窗这个是很常见的场景,有时候它不弹出来去操作的话,会抛异常。那么又不知道它啥时候会出来,那么久需要去判断弹窗是否弹出了。

    本篇接着Selenium2+python自动化42-判断元素(expected_conditions)讲expected_conditions这个模块

    一、判断alert源码分析

    class alert_is_present(object):
        """ Expect an alert to be present."""

        """判断当前页面的alert弹窗"""
        def __init__(self):
            pass

        def __call__(self, driver):
            try:
                alert = driver.switch_to.alert
                alert.text
                return alert
            except NoAlertPresentException:
                return False

    1.这个类比较简单,初始化里面无内容

    2.__call__里面就是判断如果正常获取到弹出窗的text内容就返回alert这个对象(注意这里不是返回Ture),没有获取到就返回False

    二、实例操作

    1.前面的操作步骤优化了下,为了提高脚本的稳定性,确保元素出现后操作,

    这里结合WebDriverWait里的方法:Selenium2+python自动化38-显式等待(WebDriverWait)

    2.实现步骤如下,这里判断的结果返回有两种:没找到就返回False;找到就返回alert对象

    3.先判断alert是否弹出,如果弹出就点确定按钮accept()

    三、参考代码

    # coding:utf-8
    from selenium import webdriver
    from selenium.webdriver.common.action_chains import ActionChains
    from selenium.webdriver.support.select import Select
    from selenium.webdriver.support.wait import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    driver = webdriver.Firefox()
    url = "https://www.baidu.com"
    driver.get(url)
    mouse = WebDriverWait(driver, 10).until(lambda x: x.find_element("link text", "设置"))
    ActionChains(driver).move_to_element(mouse).perform()
    WebDriverWait(driver, 10).until(lambda x: x.find_element("link text", "搜索设置")).click()
    # 选择设置项
    s = WebDriverWait(driver, 10).until(lambda x: x.find_element("id", "nr"))
    Select(s).select_by_visible_text("每页显示50条")
    # 点保存按钮
    js = 'document.getElementsByClassName("prefpanelgo")[0].click();'
    driver.execute_script(js)
    # 判断弹窗结果 交流QQ群: 232607095
    result = EC.alert_is_present()(driver)
    if result:
        print result.text
        result.accept()
    else:
        print "alert 未弹出!"

  • 相关阅读:
    Ocelot网关
    .Net Configuration配置优先级问题
    FilterContext/HttpContext 获取请求参数
    关于.Net的文件上传问题
    Notion+Zetero文献同步配置
    PyTorch训练模版
    marked ASP.NET 页面对象模型
    转:jQuery设计思想
    tryParse, try/catch(Parse), Convert比较
    CSS3 :nthchild()伪类选择器
  • 原文地址:https://www.cnblogs.com/caoj/p/7814165.html
Copyright © 2020-2023  润新知