selenium webdriver学习 07 – 如何处理alert、confirm、prompt对话框

玩技站长 Auto测试评论561字数 1959阅读模式
alert、confirm、prompt这样的js对话框在selenium1.X时代也是难啃的骨头,常常要用autoit来帮助处理。
试用了一下selenium webdriver中处理这些对话框十分方便简洁。以下面html代码为例:
Dialogs.html
        
<html>
    <head>
        <title>Alert</title>
    </head>
    <body>
        <inputid = "alert"value = "alert"type = "button"onclick = "alert('欢迎!请按确认继续!');"/>
  <inputid = "confirm"value = "confirm"type = "button"onclick = "confirm('确定吗?');"/>
  <inputid = "prompt"value = "prompt"type = "button"onclick = "var name =prompt('请输入你的名字:','请输入你的名字'); document.write(name) "/>
    </body>
</html> 
以上html代码在页面上显示了三个按钮,点击他们分别弹出alert、confirm、prompt对话框。如果在prompt对话框中输入文字点击确定之后,将会刷新页面,显示出这些文字 。
selenium webdriver 处理这些弹层的代码如下:
文章源自玩技e族-https://www.playezu.com/10904.html
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
 
public class DialogsStudy {
    /**
     * @author gongjf
     */
    publicstatic void main(String[] args) {
        // TODO Auto-generated method stub
        System.setProperty("webdriver.firefox.bin","D:\\Program Files\\Mozilla Firefox\\firefox.exe");  
        WebDriver dr = new FirefoxDriver();
        String url = "file:///C:/Documents and Settings/gongjf/桌面/selenium_test/Dialogs.html";//"/Your/Path/to/main.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没有对话框就不能用了,不然会报错。

文章源自玩技e族-https://www.playezu.com/10904.html 文章源自玩技e族-https://www.playezu.com/10904.html

 
  • 版权提示:本站仅供存储任何法律责任由作者承担▷诈骗举报◁▷新闻不符◁▷我要投稿◁
    风险通知:非原创文章均为网络投稿真实性无法判断,侵权联系2523030730
    免责声明:内容来自用户上传发布或新闻客户端自媒体,切勿!切勿!切勿!添加联系方式以免受骗。
  • 原创转载:https://www.playezu.com/10904.html
    转载说明: 点我前往阅读>>>
匿名

发表评论

匿名网友
确定