Selenium常用操作汇总二——如何处理alert、confirm、prompt对话框

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对话框中输入文字点击确定之后,将会刷新页面,显示出这些文字 。

selenium webdriver 处理这些弹层的代码如下:

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 
     */  
    public static 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没有对话框就不能用了,不然会报错。
posted @ 2018-06-21 09:27  李清欣  阅读(282)  评论(0编辑  收藏  举报