Selenium-webdriver系列教程(7)———如何处理alert和confirm

来源:互联网 发布:maxwell render mac 编辑:程序博客网 时间:2024/06/05 05:54

     当使用watir 1.6x 的时候, 处理页面javascript弹出的alertconfrim窗口时必须借助AutoIT工具来辅助执行,非常麻烦, 而且安全性不好。

但在selenium webdriver中,confirm和alert的处理再也不需要借助任何第三方工具了, 而且非常方便。

下面的html页面上有1个名为click的button,点击该button后就会弹出1个alert窗口。还有一个confirm对话框, 有兴趣的可以试试。

<html>
    <head>
        <title>Alert</title>
        <script language= "javascript" type="text/javascript">
                function clickbutton(flag)
                {
                    if (flag == 1) alert("测试alter对话框");
                    if (flag == 2) prompt("测试prompt对话框");
                    if (flag == 3) confirm('测试confirm对话框', '测试confirm对话框?',"测试结果:");
                }
            </script>
    </head>
    <body>
        <input id = "btn" value = "click" type = "button" onclick = "alert('hello');"/>
     <input type="button" name="promptbutton" value="测试prompt对话框"  onclick = "clickbutton(3);" />
    </body>
</html>


selenium webdriver处理alert的代码如下:

require 'rubygems'
require 'selenium-webdriver'
 

dr = Selenium::WebDriver.for :firefox

frame_file = 'file:///'.concat File.expand_path(File.join(File.dirname(__FILE__), 'alert.html'))
 
dr.navigate.to frame_file
 
dr.find_element(:id =>'btn').click
 
a = dr.switch_to.alert
 
puts a.text #--> hello
 
a.accept


     上面代码的代码: 先点击id为btn的按钮,然后a = dr.switch_to.alert返回了1个alert element 对象,并赋值给变量a。

这样a就代表了alert, 使用puts a.text语句可以输出alert的内容,这里就会打印出'hello'。

a.accept表示点击确认,当弹出窗口为confrim时,a.accept也表示确认,如果需要取消的话,那么则可以使用a.dismiss方法。

     使用selenium webdriver来处理对话框看起来是非常的方便, 代码简单而且高效。


原创粉丝点击