How to open a new tab using Selenium WebDriver?

Bhakti Shah picture Bhakti Shah · Jul 9, 2013 · Viewed 282.5k times · Source

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

Answer

Yi Zeng picture Yi Zeng · Jul 9, 2013

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();
        }
    }
}