如何切换到新打开的标签并关闭它?

时间:2016-02-10 07:14:26

标签: selenium selenium-webdriver webdriver

我已经使用以下两种方法切换到选项卡并关闭它。但不幸的是,它们都没有用。请提供替代方法。

SOL1:

public static void switchTab()
            {
                try{
                    webDriver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.PAGE_DOWN);
                    webDriver.close();
                    webDriver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.PAGE_DOWN);
                    }
                    catch(Exception e){

                        e.printStackTrace();}
                    }
                }

此处,驱动程序正在关闭整个浏览器,而不是关闭选项卡。

SOL2:

public void switchTab(){
try{
ArrayList<String> tabs2 = new ArrayList<String> (webDriver.getWindowHandles());

webDriver.switchTo().window(tabs2.get(1));
webDriver.close();
webDriver.switchTo().window(tabs2.get(0));
}
catch(Exception e){

    e.printStackTrace();}
}

由于没有打开其他窗口,这会抛出索引超出范围的异常。

2 个答案:

答案 0 :(得分:0)

尝试以下代码

   String homeWindow = driver.getWindowHandle();
       Set<String> allWindows = driver.getWindowHandles();

        //Use Iterator to iterate over windows
        Iterator<String> windowIterator =  allWindows.iterator();

        //Verify next window is available
        while(windowIterator.hasNext()){

            //Store the Recruiter window id
            String childWindow = windowIterator.next();

            //Here we will compare if parent window is not equal to child window 
            if (homeWindow.equals(childWindow)){
                driver.switchTo().window(childWindow);

            //switch here to your desired window/tab and perform your action
                driver.close();
            }

希望它会对你有所帮助:)。

答案 1 :(得分:0)

如果理解正确,那么这可能会有所帮助 把它放在功能块中。

    WebDriver driver = new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get("http://google.com");
    String gettitle = driver.getTitle();

    String windowHandel = driver.getWindowHandle();

    System.out.println(windowHandel + " " + gettitle);

    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL+"t");
    ArrayList tabs = new ArrayList(driver.getWindowHandles());

    System.out.println(tabs.size());
    driver.switchTo().window((String) tabs.get(0));

    gettitle ="";

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

    gettitle = driver.getTitle();
    System.out.println(tabs.get(0).toString() + " " + gettitle);


    driver.switchTo().window(windowHandel);     

    Thread.sleep(3000);

    Actions actionObj = new Actions(driver);
    actionObj.keyDown(Keys.CONTROL)
             .sendKeys(Keys.chord("w"))
             .keyUp(Keys.CONTROL)
             .perform();

    driver.switchTo().defaultContent();