Selenium处理模态对话框
问题描述:
点击按钮出现一个模态对话框,代码会卡在click这步不继续执行。原因是Selenium目前没有提供对模态对话框的处理。
解决方案:
将click出现弹出框这步用JS代替执行,然后切换到弹出窗就可以继续操作页面元素了。
测试地址:https://developer.mozilla.org/samples/domref/showModalDialog.html
代码如下:
public class junitTest {
WebDriver driver = new FirefoxDriver();
String baseUrl = "https://developer.mozilla.org/samples/domref/showModalDialog.html";
@Test
public void openModal() throws InterruptedException{
driver.get(baseUrl);
driver.findElement(By.xpath("/html/body/input")).click(); //点击后代码卡在这里
Thread.sleep(2000);
Set<String> handlers = driver.getWindowHandles();
for(String winHandler:handlers){
driver.switchTo().window(winHandler);
}
driver.findElement(By.id("foo")).sendKeys("2");
driver.findElement(By.xpath("/html/body/input[2]")).click();
}
}
click这步替换为JS执行后代码:
public class junitTest {
WebDriver driver = new FirefoxDriver();
String baseUrl = "https://developer.mozilla.org/samples/domref/showModalDialog.html";
@Test
public void openModal() throws InterruptedException{
driver.get(baseUrl);
//driver.findElement(By.xpath("/html/body/input")).click(); //点击后代码卡在这里
String js = "setTimeout(function(){document.getElementsByTagName(‘input‘)[0].click()},100)";
((JavascriptExecutor)driver).executeScript(js);
Thread.sleep(2000);
Set<String> handlers = driver.getWindowHandles();
for(String winHandler:handlers){
driver.switchTo().window(winHandler);
}
driver.findElement(By.id("foo")).sendKeys("2");
driver.findElement(By.xpath("/html/body/input[2]")).click();
}
}