码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-11-10 15:17:00      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:保存   expected   比较   www.   als   import   ref   wait   obj   

前言

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

本篇接着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 未弹出!"

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

标签:保存   expected   比较   www.   als   import   ref   wait   obj   

原文地址:http://www.cnblogs.com/caoj/p/7814165.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!