Selenium对于对话框alert,confirm,prompt的处理
html 源码:
<html>
<head>
<title>Alert</title>
<script>
function myFunction()
{
var x;
var b = prompt("hello","harry potter");
if (b!=null && b!="") {
x = "hello"+b+"欢迎你";
}
document.getElementById("display").innerHTML=x;
}
</script>
</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 = "myFunction()" />
<p id = "display"></p>
</body>
</html>
以上html代码在页面上显示了三个按钮,点击他们分别弹出alert、confirm、prompt对话框。如果在prompt对话框中输入文字点击确定之后,将会刷新页面,显示出这些文字
- import org.openqa.selenium.Alert;
- import org.openqa.selenium.By;
- import org.openqa.selenium.WebDriver;
- import org.openqa.selenium.firefox.FirefoxDriver;
- public class DialogsStudy {
- /**
- * @wuyepiaoxue
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- System.setProperty("webdriver.firefox.bin","D:/Program Files (x86)/Mozilla Firefox/firefox.exe");
- WebDriver dr = new FirefoxDriver();
- String url = "file:///C:/Users/Administrator/Desktop/test.htm";
- 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();
- }
-
}