問題描述:
點擊按鈕出現一個模態(tài)對話框,代碼會卡在click這步不繼續(xù)執(zhí)行。原因是Selenium目前沒有提供對模態(tài)對話框的處理。
解決方案:
將click出現彈出框這步用JS代替執(zhí)行,然后切換到彈出窗可以繼續(xù)操作頁面元素了。
測試地址: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執(zhí)行后代碼:
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();
}
}