码迷,mamicode.com
首页 > 其他好文 > 详细

Selenium->如何处理alert、confirm、prompt对话框

时间:2014-11-19 20:10:05      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:style   blog   ar   color   os   sp   on   div   log   

alert、confirm、prompt这样的js对话框在selenium1.X时代也是难啃的骨头,常常要用autoit来帮助处理。
试用了一下selenium webdriver中处理这些对话框十分方便简洁。以下面html代码为例:

Dialogs.html

<html>
<head>
  <title>Alert</title>
</head>
<body>
  <input id = "alert" value = "alert" type = "button" onclick = "alert(‘欢迎!请按确认继续!‘);
  <input id = "confirm" value = "confirm" type = "button" onclick = "confirm(‘确定吗?‘);"/>
  <input id = "prompt" value = "prompt" type = "button" onclick = "var name = prompt(‘请输入你
你的名字‘); document.write(name) "/>
</body>
</html>

以上html代码在页面上显示了三个按钮,点击他们分别弹出alert、confirm、prompt对话框。如果在prompt
对话框中输入文字点击确定之后,将会刷新页面,显示出这些文字 。

public static void main(String[] args) {
        
        WebDriver dr = new FirefoxDriver();
        
        String url = "file:///C:/Documents and Settings/gongjf/桌面/selenium_test/Dialogs.html";
        
        dr.get(url);
        
        //点击第一个按钮,输出对话框上面的文字,然后叉掉
        dr.findElement(By.id("alert")).click();
        
        Alert alert = dr.switchTo().alert();
        
        String text = alert.getText();
        
        System.out.println(text);
        
        alert.dismiss();
        
        //点击第二个按钮,输出对话框上面的文字,然后点击确认
        dr.findElement(By.id("confirm")).click();
        
        Alert confirm = dr.switchTo().alert();
        
        String text1 = confirm.getText();
        
        System.out.println(text1);
        
        confirm.accept();
        
        //点击第三个按钮,输入你的名字,然后点击确认,最后
        dr.findElement(By.id("prompt")).click();

        Alert prompt = dr.switchTo().alert();
        
        String text2 = prompt.getText();
        
        System.out.println(text2);
        
        prompt.sendKeys("jarvi");
        
        prompt.accept();
    }

从以上代码可以看出dr.switchTo().alert();这句可以得到alert\confirm\prompt对话框的对象,然后运用其方法
对它进行操作。对话框操作的主要方法有:

 

• getText() 得到它的文本值
• accept() 相当于点击它的"确认"
• dismiss() 相当于点击"取消"或者叉掉对话框
• sendKeys() 输入值,这个alert\confirm没有对话框就不能用了,不然会报错。

 

Selenium->如何处理alert、confirm、prompt对话框

标签:style   blog   ar   color   os   sp   on   div   log   

原文地址:http://www.cnblogs.com/LoveTest/p/4108860.html

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