How to open a new tab using Selenium WebDriver?

后端 未结 29 2395
野的像风
野的像风 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:39

    *JAVA

    I recommend to using JavascriptExecutor:

    • Open new blank window:
    ((JavascriptExecutor) driver).executeScript("window.open()");
    
    • Open new window with specific url:
    ((JavascriptExecutor) driver).executeScript("window.open('https://google.com')");
    

    Following import:

    import org.openqa.selenium.JavascriptExecutor;
    
    0 讨论(0)
  • 2020-11-22 05:39
    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
    
    ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
    
    driver.switchTo().window(tabs.get(0));
    
    0 讨论(0)
  • 2020-11-22 05:40

    Just for anyone else who's looking for an answer in Ruby/Python/C# bindings (Selenium 2.33.0).

    Note that the actual keys to send depend on your OS, for example, Mac uses COMMAND + t, instead of CONTROL + t.

    Ruby

    require 'selenium-webdriver'
    
    driver = Selenium::WebDriver.for :firefox
    driver.get('http://stackoverflow.com/')
    
    body = driver.find_element(:tag_name => 'body')
    body.send_keys(:control, 't')
    
    driver.quit
    

    Python

    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    
    driver = webdriver.Firefox()
    driver.get("http://stackoverflow.com/")
    
    body = driver.find_element_by_tag_name("body")
    body.send_keys(Keys.CONTROL + 't')
    
    driver.close()
    

    C#

    using OpenQA.Selenium;
    using OpenQA.Selenium.Firefox;
    
    namespace StackOverflowTests {
    
        class OpenNewTab {
    
            static void Main(string[] args) {
    
                IWebDriver driver = new FirefoxDriver();
                driver.Navigate().GoToUrl("http://stackoverflow.com/");
    
                IWebElement body = driver.FindElement(By.TagName("body"));
                body.SendKeys(Keys.Control + 't');
    
                driver.Quit();
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:40

    To open a new tab in the existing Chrome browser using Selenium WebDriver you can use this code:

    driver.FindElement(By.CssSelector("body")).SendKeys(Keys.Control + "t");        
    string newTabInstance = driver.WindowHandles[driver.WindowHandles.Count-1].ToString();
    driver.SwitchTo().Window(newTabInstance);
    driver.Navigate().GoToUrl(url);
    
    0 讨论(0)
  • 2020-11-22 05:40

    This line of code will open a new browser tab using selenium webdriver

    ((JavascriptExecutor)getDriver()).executeScript("window.open()");
    
    0 讨论(0)
提交回复
热议问题