pythonmacosselenium

Open and close new tab with Selenium WebDriver in OS X


I'm using the Firefox Webdriver in Python 2.7 on Windows to simulate opening (Ctrl+t) and closing (Ctrl + w) a new tab.

Here's my code:

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

browser = webdriver.Firefox()
browser.get('https://www.google.com')
main_window = browser.current_window_handle
# open new tab
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
browser.get('https://www.yahoo.com')

# close tab
browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')

How to achieve the same on a Mac? Based on this comment one should use browser.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't') to open a new tab but I don't have a Mac to test it and what about the equivalent of Ctrl-w?

Thanks!


Solution

  • There's nothing easier and clearer than just running JavaScript.

    Open new tab: driver.execute_script("window.open('');")