WebDriver中处理原生JS的 alert confirm 以及prompt是很方便的(虽然现在原生JS的实现方式用的很少了。具体思路是使用switchTo.alert()方法定位到当前的 alert/confirm/prompt(这里注意当前页面只能同时含有一个控件,如果多了会报错的,所以这就需要一一处理了),然后在调用Alert 的方法进行操作,Alert提供了以下几个方法:
- getText : 返回alert/confirm/prompt中的文字内容
- accept : 点击确认按钮
- dismiss : 点击取消按钮如果有取消按钮的话
- sendKeys : 向prompt中输入文字 //这个方法在chromedriver中不起作用,IE的话由于家中无Windows没有做demo.
下面是测试页面alert_demo.html源代码123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
packageorg.coderinfo.demo;importorg.openqa.selenium.Alert;importorg.openqa.selenium.By;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.firefox.FirefoxDriver;publicclassAlertDemo {privatestaticfinalString URL ="file:///home/moon/Desktop/alert_demo.html";/*** @author CoderInfo*/publicstaticvoidmain(String[] args)throwsInterruptedException {WebDriver driver =newFirefoxDriver();//创建一个firefox的 webdriverdriver.get(URL);driver.manage().window().maximize();Thread.sleep(1000);// 点击弹出alertdriver.findElement(By.id("alert")).click();Thread.sleep(3000);Alert alert = driver.switchTo().alert();//捕获alertalert.accept();//点击确认按钮Thread.sleep(3000);//等待3s//点击弹出confirmdriver.findElement(By.id("confirm")).click();Thread.sleep(3000);Alert confirm = driver.switchTo().alert();//捕获confirmString confirmText = confirm.getText();//获取confirm中的文字信息System.out.println(confirmText);confirm.accept();//confirm 点击确认按钮// confirm.dismiss(); //confirm点击取消按钮Thread.sleep(3000);//点击弹出promptdriver.findElement(By.id("prompt")).click();Thread.sleep(3000);Alert prompt = driver.switchTo().alert();//捕获prompt// String promptText = prompt.getText(); //获取prompt中的文字信息// System.out.println(promptText);prompt.sendKeys("可能是由于太懒了");//向prompt中输入内容Thread.sleep(3000);prompt.accept();//prompt 点击确认按钮// prompt.dismiss(); //prompt点击取消按钮Thread.sleep(3000);driver.quit();// close webdriver}}12345678910111213141516171819202122232425<html><head><title>Alert</title><scripttype="text/javascript">function testAlert(){alert("测试Alert");}function testConfirm(){confirm("你喜欢自动化测试吗?");}function testPrompt(){var content = prompt("你为什么喜欢自动化?");document.write(content);}</script></head><body><h2>Test Alert</h2><inputtype="button"value="alert"onclick="testAlert()"id="alert"/><inputtype="button"value="confirm"onclick="testConfirm()"id="confirm"/><inputtype="button"value="prompt"onclick="testPrompt()"id="prompt"/></body></html>
原文链接:http://my.oschina.net/coderinfo/blog/200515
本文介绍如何使用WebDriver处理原生JavaScript的alert、confirm和prompt对话框,包括如何通过switchTo.alert()方法定位并操作这些对话框,以及使用Alert类的方法如accept、dismiss和sendKeys进行相应操作。
167

被折叠的 条评论
为什么被折叠?



