How do I switch to the active tab in Selenium?

This actually worked for me in 3.x:

driver.switch_to.window(driver.window_handles[1])

window handles are appended, so this selects the second tab in the list

to continue with first tab:

driver.switch_to.window(driver.window_handles[0])

The accepted answer didn't work for me.
To open a new tab and have selenium switch to it, I used:

driver.execute_script('''window.open("https://some.site/", "_blank");''')
sleep(1) # you can also try without it, just playing safe
driver.switch_to.window(driver.window_handles[-1]) # last opened tab handle  
# driver.switch_to_window(driver.window_handles[-1]) # for older versions

if you need to switch back to the main tab, use:

driver.switch_to.window(driver.window_handles[0])

Summary:

The window_handles contains a list of the handles of opened tabs, use it as argument in switch_to.window() to switch between tabs.


Pressing ctrl+t or choosing window_handles[0] assumes that you only have one tab open when you start.

If you have multiple tabs open then it could become unreliable.

This is what I do:

old_tabs=self.driver.window_handles
#Perform action that opens new window here
new_tabs=self.driver.window_handles
for tab in new_tabs:
     if tab in old tabs:
          pass
     else:
          new_tab=tab
driver.switch_to.window(new_tab)

This is something that would positively identify the new tab before switching to it and sets the active window to the desired new tab.

Just telling the browser to send ctrl+tab does not work because it doesn't tell the webdriver to actually switch to the new tab.


Some possible approaches:

1 - Switch between the tabs using the send_keys (CONTROL + TAB)

self.driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

2 - Switch between the tabs using the using ActionsChains (CONTROL+TAB)

actions = ActionChains(self.driver)      
actions.key_down(Keys.CONTROL).key_down(Keys.TAB).key_up(Keys.TAB).key_up(Keys.CONTROL).perform()

3 - Another approach could make usage of the Selenium methods to check current window and move to another one:

You can use

driver.window_handles

to find a list of window handles and after try to switch using the following methods.

- driver.switch_to.active_element      
- driver.switch_to.default_content
- driver.switch_to.window

For example, to switch to the last opened tab, you can do:

driver.switch_to.window(driver.window_handles[-1])