zoukankan      html  css  js  c++  java
  • 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 未弹出!"

  • 相关阅读:
    IOS Date, NSDateFormatter, compare, dateFromString:mydatestr
    IOS Retain,nil,alloc,init
    IOS NSArray,NSDictionary
    object c基础, 基本类型(NSString,char*NSDate,NSData),集合NSArray,NSMutableArray,NSDictionary,NSMutableDictionary,NSSet,NSMutableSet
    IOS UIProgressView 用法
    UIButton 用法
    XCode 快捷键,MAC 快捷键
    苹果软件系列产品介绍
    android 之多线程应用[message,messagequeue,handler,looper,asynchtask]
    Linux查看程序被哪个端口占用
  • 原文地址:https://www.cnblogs.com/caoj/p/7814165.html
Copyright © 2011-2022 走看看