Working with tabs in WebDriver can be infuriating; but once you understand the underlying logic it's a breeze.

How do tabs work in WebDriver?

  1. When WebDriver instantiates a browser, a list object named window_handles is created.
  2. Instantiating WebDriver results in a tab being opened and added to the list window_handles.
  3. Calling driver.window_handles returns a list which contains your tabs.
  4. When tabs are created or closed, they are added/removed from the list.


Switching to the last opened tab.

In WebDriver, a link click that results in a new tab opening places the newly opened tab at the end of a list.

This list is accessible through calling driver.window_handles. You can easily access the most recently opened tab by calling driver.window_handles[-1].

from selenium import webdriver

driver = webdriver.Chrome()  

# Find the object to interact with.

# New tabs will be the last object in window_handles

# close the tab

# switch to the main window

© 2017. All Rights Reserved.