前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Selenium2+python自动化47-判断弹出框存在(alert_is_present)

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

作者头像
上海-悠悠
发布2018-04-08 15:54:37
5.5K0
发布2018-04-08 15:54:37
举报
文章被收录于专栏:从零开始学自动化测试

前言

系统弹窗这个是很常见的场景,有时候它还没弹出来去操作的话,会抛异常,这就需要去判断弹窗是否弹出了。

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

一、判断alert源码分析

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

代码语言:javascript
复制
    """判断当前页面的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()

三、参考代码

代码语言:javascript
复制
# 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 未弹出!"
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2017-03-20,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 从零开始学自动化测试 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档