例子:
<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>
package web;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
/**
*
* @author 陈秀娜
* 如何处理alert、confirm、prompt
* • getText() 得到它的文本值
• accept() 相当于点击它的"确认"
• dismiss() 相当于点击"取消"或者叉掉对话框
• sendKeys() 输入值,这个alert\confirm没有对话框就不能用了,不然会报错。
*
*/
public class DialogsStudy {
public static void main(String [] args) throws InterruptedException{
WebDriver dr;
System.setProperty("webdriver.firefox.bin","D:/Program Files/Mozilla Firefox/firefox.exe" );
dr = new FirefoxDriver();
dr.get("file:///D:/dialogs.html");
//点击第一个按钮,输出对话框上面的文字,然后叉掉;
dr.findElement(By.id("alert")).click();
Alert alert = dr.switchTo().alert();
String text = alert.getText();
System.out.println(text);
Thread.sleep(3000);
alert.dismiss();//关掉弹窗;
//点击第二个按钮,输出对话框上面的文字,然后点击确认
dr.findElement(By.id("confirm")).click();
Alert confirm = dr.switchTo().alert();
String text1 = confirm.getText();
System.out.println(text1);
Thread.sleep(3000);
confirm.accept();
//点击第三个按钮,输入你的名字,然后点击确认,最后
dr.findElement(By.id("prompt")).click();
Alert prompt = dr.switchTo().alert() ;
String text2 = prompt.getText();
System.out.println(text2);
prompt.sendKeys("chenxn");
prompt.accept();
Thread.sleep(3000);
dr.quit();
}
}