How to open a new tab using Selenium WebDriver?

后端 未结 29 2819
野的像风
野的像风 2020-11-22 04:40

How to open a new tab in the existing Firefox browser using Selenium WebDriver (a.k.a. Selenium 2)?

29条回答
  •  耶瑟儿~
    2020-11-22 05:35

    I am using Selenium 2.52.0 in Java and Firefox 44.0.2. Unfortunately none of above solutions worked for me. The problem is if I a call driver.getWindowHandles() I always get 1 single handle. Somehow this makes sense to me as Firefox is a single process and each tab is not a separate process. But maybe I am wrong. Anyhow I try to write my own solution:

            // open a new tab
            driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
    
            //url to open in a new tab
            String urlToOpen = "https://url_to_open_in_a_new_tab";
    
            Iterator windowIterator = driver.getWindowHandles()
                    .iterator();
            //I always get handlesSize == 1, regardless how many tabs I have
            int handlesSize = driver.getWindowHandles().size();
    
            //I had to grab the original handle
            String originalHandle = driver.getWindowHandle();
    
            driver.navigate().to(urlToOpen);
    
            Actions action = new Actions(driver);
            // close the newly opened tab
            action.keyDown(Keys.CONTROL).sendKeys("w").perform();
            // switch back to original
            action.keyDown(Keys.CONTROL).sendKeys("1").perform();
    
            //and switch back to the original handle. I am not sure why, but
            //it just did not work without this, like it has lost the focus
            driver.switchTo().window(originalHandle);
    

    I used Ctrl+t combination to open a new tab, Ctrl+w to close it, and to switch back to original tab I used Ctrl+1 (the first tab). I am aware that mine solution is not perfect or even good and I would also like to switch with driver's switchTo call, but as I wrote it was not possible as I had only one handle. Maybe this will be helpful to someone with the same situation.

提交回复
热议问题