Selenium处理模态对话框-自动化测试
更新时间:2022-04-29 09:15:57 作者:多测师 浏览:319
问题描述:
点击按钮出现一个模态对话框,代码会卡在click这步不继续执行。原因是Selenium目前没有提供对模态对话框的处理。
解决方案:
将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(); //点击后代码卡在这里
Thread.sleep(2000);
Set 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 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();
}
}
以上内容为大家介绍了自动化测试中的Selenium处理模态对话框,本文由多测师亲自撰写,希望对大家有所帮助。了解更多自动化测试相关知识:https://www.aichudan.com/xwzx/