1

I just installed Selenium Web Driver and tried it out. It works great. My use case can be describe as followed:

  1. Start Firefox on a server with pseudo X server (Xvfb)
  2. New Driver.Firefox() object
  3. Open 10 tabs and load a webpage in each tab
  4. Retrieve the html from all loaded pages

The only step that is not working is step 3. I can not find out how to open new tabs. I found this here on SO : How to open a new tab using Selenium WebDriver with Java? However, I tested this locally (i.e. with visible display) on my Mac for debugging purpose and I saw that the Firefox browser (which was opened when creating the driver object) does not open any tabs when doing as described on the SO thread. So I tried this here:

driver = webdriver.Firefox()
driver.get("https://stackoverflow.com/")
body = driver.find_element_by_tag_name("body")
body.send_keys(Keys.CONTROL + 't')

As I said, it does not work for me. So, how else is it possible to open tabs? I use Selenium 2.39 (pip install selenium) and Python 2.7.

Community
  • 1
  • 1
toom
  • 12,864
  • 27
  • 89
  • 128

2 Answers2

4

the key combination to open a new tab on OSX is Command+T, so you should use

body.send_keys(Keys.COMMAND + 't') 
Smart Huang
  • 156
  • 2
2

It's probably slightly more correct to send it to the browser via action chaining since you're not actually typing text; this also makes your code more readable imo

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

# before correction from  DMfll:
# ActionChains(driver).send_keys(Keys.COMMAND, "t").perform()

# correct method
ActionChains(driver).key_down(Keys.COMMAND).send_keys("t").key_up(Keys.COMMAND)‌​‌​.perform()
sam-6174
  • 3,104
  • 1
  • 33
  • 34
  • 1
    I wasn't quite getting the expected behavior from `ActionChains(driver).send_keys(Keys.COMMAND, "t").perform()` . This gave me the expected behavior as documented here: [http://selenium-python.readthedocs.org/en/latest/api.html#module-selenium.webdr‌​iver.common.action_chains](http://selenium-python.readthedocs.org/en/latest/api.html#module-selenium.webdr‌​iver.common.action_chains): `ActionChains(driver).key_down(Keys.COMMAND).send_keys("t").key_up(Keys.COMMAND)‌​.perform()`. It includes a key up and a key down. – dmmfll Jul 27 '15 at 11:54