Open and close a new tab using Selenium Webdriver in OSx

I am using Firefox Webdriver in Python 2.7 for Windows to simulate opening ( Ctrl+ t) and closing ( Ctrl+ w) of a new tab

Here is 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 thing on a Mac? Based on this comment , it should be used 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 check it and what is equivalent Ctrl-w?

Thank!

+4
source share
3 answers

There is nothing simpler and clearer than just running JavaScript.

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

+4
source

open a new tab:

browser.get('http://www.google.com')

close tab:

browser.close()

:

browser.swith_to_window(window_name)
+2

:

browser.execute_script("window.open('"+your url+"', '_blank')")

:

browser.switch_to.window(windows[1])
0
source

All Articles