Chromedriver不会打开链接新的选项卡或窗口,而是在当前选项卡/窗口中打开预期的链接

时间:2017-01-15 20:53:14

标签: java selenium selenium-webdriver selenium-chromedriver

这是我试图处理窗口的代码,但是谷歌选项卡中打开的网址。

System.setProperty("webdriver.chrome.driver", "/home/ish/chromedriver");    

WebDriver driver =new ChromeDriver();

driver.get("http://google.com");
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL+"n");
try {
    Thread.sleep(3000);
    for(String windowHandle:driver.getWindowHandles()) {
        driver.switchTo().window(windowHandle);
    }
    driver.get("http://fb.com");
} catch (Exception e) {
    System.out.println(e);
}

2 个答案:

答案 0 :(得分:0)

在窗口句柄上的迭代中,您将切换到它们。最后一个开关将焦点返回到第一个窗口,链接将在那里打开。

您应该只切换到新窗口

System.setProperty("webdriver.chrome.driver", "/home/ish/chromedriver");    

WebDriver driver = new ChromeDriver();

driver.get("http://google.com");

String firstWindowHandle = driver.getWindowHandle();

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL+"n");
try {
    Thread.sleep(3000);
    for(String windowHandle : driver.getWindowHandles()) {
        if (!windowHandle.equals(firstWindowHandle)) {
            driver.switchTo().window(windowHandle);
        }
    }
    driver.get("http://fb.com");
} catch (Exception e) {
    System.out.println(e);
}

答案 1 :(得分:0)

驱动程序在同一个窗口中打开,因为for循环正在切换旧句柄

代码可能如下所示

System.setProperty("webdriver.chrome.driver", "/home/ish/chromedriver");    

WebDriver driver =new ChromeDriver();

driver.get("http://google.com");
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL+"n");
        String currentHandle = driver.getWindowHandle();
        try {
            Thread.sleep(3000);
            for(String windowHandle:driver.getWindowHandles()) {
                if(!currentHandle.equals(windowHandle)){
                   driver.switchTo().window(windowHandle);
                   break;
                }
            }
            driver.get("http://fb.com");
        } catch (Exception e) {
            System.out.println(e);
        }