alert、confirm、prompt这样的js对话框在selenium webdriveriver中处理十分方便简洁。以下面html代码为例:
example.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('确定?');"/>
<inputid = "prompt" value = "prompt" type = "button"onclick = "var name = prompt('请输入内容:','请输入
内容'); document.write(name) "/>
</body>
</html>
以上html代码在页面上显示了三个按钮,点击他们分别弹出alert、confirm、prompt对话框。如果在prompt对话框中输入文字点击确定之后,将会刷新页面,显示这些文字 。
selenium webdriveriver 处理这些弹层的代码如下:
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriveriver;
import org.openqa.selenium.firefox.FirefoxDriveriver;
public class Alertpop{
/**
* @author tyf
*/
publicstatic void main(String[] args) {
//TODO Auto-generated method stub
WebDriveriver driver = new FirefoxDriveriver();
Stringurl = "file:///C:/selenium/Example.html";//Example.html文件所在的路径
driver.get(url);
//点击第一个按钮,输出对话框上面的文字
driver.findElement(By.id("alert")).click();
Alertalert = driver.switchTo().alert();
Stringtext = alert.getText();
System.out.println(text);
alert.dismiss();//关闭alert
//点击第二个按钮,输出对话框上面的文字,然后确认
driver.findElement(By.id("confirm")).click();
Alertconfirm = driver.switchTo().alert();
Stringtext1 = confirm.getText();
System.out.println(text1);
confirm.accept();
//点击第三个按钮,输入你的名字,然后点击确认
driver.findElement(By.id("prompt")).click();
Alertprompt = driver.switchTo().alert();
Stringtext2 = prompt.getText();
System.out.println(text2);
prompt.sendKeys("jarvi");
prompt.accept();
}
}
从以上代码可以看出driver.switchTo().alert();这句可以得到alert\confirm\prompt对话框的对象,然后运用其方法对它进行操作。对话框操作的主要方法有:
- getText() 得到文本内容
- accept() 相当于点击它的"确认"
- dismiss() 相当于点击"取消"对话框
- sendKeys() 输入值,这个alert\confirm没有对话框就不能用了,不然会报错。