我正在使用driver.getWindowHandle()
来切换窗口。这在 Chrome 中工作正常但在 Firefox 中单击打开新窗口的按钮后,执行不会继续,也不会停止。我该如何解决?
编辑: - 评论中共享的代码 -
String parentWindow = driver.getWindowHandle();
driver.findElement(By.id("mybutton")).click();
Set<String> handles = driver.getWindowHandles();
代码:
String parentWindow = driver.getWindowHandle();
driver.findElement(By.id("myButton")).click();
Set<String> handles = driver.getWindowHandles();
for (String windowHandle : handles) {
if (!windowHandle.equals(parentWindow)) {
driver.switchTo().window(windowHandle);
//call methods
}
}
driver.switchTo().window(parentWindow); // cntrl to parent window
答案 0 :(得分:0)
使用Selenium 2.53.1使用firefox 47.0.1作为Java中的WebDriver:您需要在其自己的驱动程序中打开单独的窗口/浏览器。我有同样的问题。无论我打开多少个窗口或标签,&#34; driver.getWindowHandles()&#34;只返回一个句柄,因此无法在标签之间切换。我发现Chrome对我来说更好。
一旦我开始使用Chrome 51.0,我就可以获得所有句柄。以下代码显示了如何访问每个驱动程序中的多个驱动程序和多个选项卡。
// INITIALIZE TWO DRIVERS (THESE REPRESENT SEPARATE CHROME WINDOWS/BROWSERS)
driver1 = new ChromeDriver();
driver2 = new ChromeDriver();
// LOOP TO OPEN AS MANY TABS AS YOU WISH
for(int i = 0; i < TAB_NUMBER; i++) {
driver1.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
// SLEEP FOR SPLIT SECOND TO ALLOW DRIVER TIME TO OPEN TAB
Thread.sleep(100);
// STORE TAB HANDLES IN ARRAY LIST FOR EASY ACCESS
ArrayList tabs1 = new ArrayList<String> (driver1.getWindowHandles());
// REPEAT FOR THE SECOND DRIVER (SECOND CHROME BROWSER WINDOW)
// LOOP TO OPEN AS MANY TABS AS YOU WISH
for(int i = 0; i < TAB_NUMBER; i++) {
driver2.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
// SLEEP FOR SPLIT SECOND TO ALLOW DRIVER TIME TO OPEN TAB
Thread.sleep(100);
// STORE TAB HANDLES IN ARRAY LIST FOR EASY ACCESS
ArrayList tabs2 = new ArrayList<String> (driver2.getWindowHandles());
// NOW PERFORM DESIRED TASKS WITH FIRST BROWSER IN ANY TAB
for(int ii = 0; ii <= TAB_NUMBER; ii++) {
driver2.switchTo().window(tabs2.get(ii));
// LOGIC FOR THAT DRIVER'S CURRENT TAB
}
// PERFORM DESIRED TASKS WITH SECOND BROWSER IN ANY TAB
for(int ii = 0; ii <= TAB_NUMBER; ii++) {
drvier2.switchTo().window(tabs2.get(ii));
// LOGIC FOR THAT DRIVER'S CURRENT TAB
}
希望这能让您更好地了解如何在多个浏览器窗口中操作多个选项卡。