16

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!

Ratmir Asanov
  • 5,889
  • 5
  • 24
  • 38
user2314737
  • 24,359
  • 17
  • 91
  • 104

5 Answers5

13

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

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

J0e3gan
  • 8,570
  • 9
  • 52
  • 78
Bek
  • 162
  • 2
  • 3
  • 2
    Hi thanks very much! But your command opens a new window, not a new tab. If you show me how to open a new tab with JS I'll accept your answer. – user2314737 Jan 16 '15 at 11:01
11

You can choose which window you want to close:

window_name = browser.window_handles[0]

Switch window:

browser.switch_to.window(window_name=window_name)

Then close it:

browser.close()
JayHung
  • 149
  • 1
  • 6
10

open a new tab:

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

close a tab:

browser.close()

switch to a tab:

browser.swith_to_window(window_name)
alien_frog
  • 548
  • 5
  • 9
  • +1 for browser.close(); I presumed this was to do trash collection on the browser object and did not realize it was a method for closing tabs – Steve Byrne Sep 28 '17 at 20:50
  • @StevenByrne Actually it will cause memory leak if you do not quit the process manually(for example, in python `sys.exit(0)`) after loop runs, no matter `driver.close()` or `driver.quit()`. – alien_frog Oct 09 '17 at 06:46
  • Sorry my bad. `driver.quit()` will prevent memory leak. And when you have only 1 tab, `driver.close()` is equal to `driver.quit()`. – alien_frog Oct 09 '17 at 06:56
6

Just to combine the answers above for someone still curious. The below is based on Python 2.7 and a driver in Chrome.

Open new tab by: driver.execute_script("window.open('"+URL+"', '__blank__');") where URL is a string such as "http://www.google.com".

Close tab by: driver.close() [Note, this also doubles as driver.quit() when you only have 1 tab open].

Navigate between tabs by: driver.switch_to_window(driver.window_handles[0]) and driver.switch_to_window(driver.window_handles[1]).

mousetail
  • 4,536
  • 2
  • 18
  • 36
3mrsh
  • 73
  • 1
  • 7
2

Open new tab:

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

Switch to new tab:

browser.switch_to.window(windows[1])
Gerry
  • 9,989
  • 3
  • 31
  • 38
ZijiG
  • 21
  • 1