Selenium处理模态对话框

发表于:2015-5-19 14:56

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:jigang_c    来源:51Testing软件测试网采编

  问题描述:
  点击按钮出现一个模态对话框,代码会卡在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();
}
}
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号