【问题标题】:How to Open new browser Window without closing previous window using selenium webdriver如何使用 selenium webdriver 打开新的浏览器窗口而不关闭以前的窗口
【发布时间】:2018-03-23 11:25:11
【问题描述】:

我正在使用下面的代码打开新的浏览器窗口,但它正在同一个选项卡中打开链接:-(。我想打开新的浏览器窗口并清除所有 cookie 而无需关闭第一个窗口。

    `      Actions act = new Actions(driver);
    act.keyDown(Keys.CONTROL).sendKeys("N").build().perform();
    driver.get("https://www.facebook.com");`

我也试过这段代码,但它没有帮助我: Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_N); driver.get("https://www.facebook.com");

任何帮助都会得到帮助!

【问题讨论】:

    标签: selenium-webdriver


    【解决方案1】:

    首先是您打开新窗口的组合键不正确。正确的组合键是 Control + N

    当你打开新窗口时,你需要聚焦到那个新窗口

    您可以使用下面的代码 sn-p 打开一个新的浏览器窗口并导航到一个 url。这是使用java.awt.Robot 包中的Robot 类。

    public void openNewWindow(String url) throws AWTException {
    
        // Initialize the robot class object
        Robot robot = new Robot();
    
        // Press and hold Control and N keys
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_N);
    
        // Release Control and N keys
        robot.keyRelease(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_N);
    
        // Set focus to the newly opened browser window
        ArrayList <String> tabs = new ArrayList<String> (driver.getWindowHandles());
        driver.switchTo().window(tabs.get(tabs.size()-1));
        for (String windowHandle : driver.getWindowHandles()) {
            driver.switchTo().window(windowHandle);
        }
    
        // Continue your actions in the new browser window
        driver.get(url);
    }
    

    【讨论】:

      【解决方案2】:

      要启动浏览器的新实例,请实现以下代码示例:

      // Store the current window url
      String url = driver.getCurrentUrl();
      
      // Create a new instance to open a new window
      WebDriver driver2 = new FirefoxDriver();    // Use your own browser driver that you are using
      
      // Go to the intended page [i.e, foo or some other link]
      driver2.navigate().to(foo);
      
      // Continue your code here in the new window...
      
      // Close the popup window now
      driver2.quit();
      
      // No need to switch back to the main window; driver is still valid.
      // demonstrate that the initial driver is still valid.
      url = driver.getCurrentUrl();
      

      【讨论】:

      • WebDriver driver2 = new FirefoxDriver();我无法实例化浏览器。我正在使用 TestNG 框架并且只实例化了一次浏览器。如果有其他出路,请告诉我。
      【解决方案3】:

      您可以使用以下java脚本打开新窗口:

      ((JavascriptExecutor)driver).executeScript("window.open(arguments[0])", "URL to open");

      【讨论】:

      • 感谢您的回复!!但是这种方法是在同一个旧选项卡中打开新链接。我想在新浏览窗口(浏览器的新实例)中打开新链接说(facebook.com)而不关闭上一个窗口。
      • 这会打开一个新标签,但不会根据问题打开一个新的浏览器窗口。
      最近更新 更多