下面代码中介绍了告警框的处理方法
1 package com.test.alerthandle; 2 3 import org.openqa.selenium.By; 4 import org.openqa.selenium.JavascriptExecutor; 5 import org.openqa.selenium.TimeoutException; 6 import org.openqa.selenium.WebDriver; 7 import org.openqa.selenium.firefox.FirefoxDriver; 8 import org.openqa.selenium.support.ui.ExpectedConditions; 9 import org.openqa.selenium.support.ui.WebDriverWait; 10 11 public class AlterHandle { 12 13 public static void main(String[] args) { 14 WebDriver driver = new FirefoxDriver(); 15 driver.get("file:///D:/10-selenium/workspace/SeleniumTest/src/com/test/alerthandle/alert.html"); 16 driver.manage().window().maximize(); 17 18 driver.findElement(By.cssSelector("#altertest")).click(); 19 20 try { 21 // 先等待prompt框的出现,然后输入内容 22 new WebDriverWait(driver, 5).until(ExpectedConditions.alertIsPresent()); 23 driver.switchTo().alert().sendKeys("处理告警框的例子"); 24 25 // 确认输入内容 26 waitTime(3000); 27 driver.switchTo().alert().accept(); 28 29 // 获取Alert框内text内容 30 waitTime(2000); 31 new WebDriverWait(driver, 5).until(ExpectedConditions.alertIsPresent()); 32 String inputInfo = driver.switchTo().alert().getText(); 33 System.out.println(inputInfo); 34 35 // 关闭Alert框 36 waitTime(3000); 37 driver.switchTo().alert().accept(); 38 39 // 利用js构造一个confirm框 40 waitTime(3000); 41 String js = "confirm("这就是一个告警框的例子")"; 42 ((JavascriptExecutor) driver).executeScript(js); 43 44 // 取消confirm框 45 waitTime(3000); 46 driver.switchTo().alert().dismiss(); 47 48 waitTime(3000); 49 driver.quit(); 50 51 } catch (TimeoutException e) { 52 driver.quit(); 53 } 54 55 } 56 57 static public void waitTime(int time) { 58 59 try { 60 Thread.sleep(time); 61 } catch (InterruptedException e) { 62 // TODO Auto-generated catch block 63 e.printStackTrace(); 64 } 65 } 66 67 }
实例例子:
1 <html> 2 <head> 3 <meta http-equiv="content-type" content="text/html;charset=utf-8" /> 4 <title>Alter</title> 5 <link 6 href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css" 7 rel="stylesheet" /> 8 </head> 9 <body> 10 <button id="altertest" onclick="disp_alert()">this is an alter</button> 11 <script type="text/javascript"> 12 function disp_alert() { 13 var a=prompt("请输入信息:",""); 14 alert("你输入的信息是:" + a ); 15 } 16 </script> 17 </body> 18 <script 19 src="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.js"></script> 20 </html>