Overview

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.

Examples

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()  
driver.get("http://example.com/")

# Find the object to interact with.
driver.find_element_by_class_name("foo").click()

# New tabs will be the last object in window_handles
driver.switch_to.window(driver.window_handles[-1])

# close the tab
driver.close()

# switch to the main window
driver.switch_to.window(driver.window_handles[0])  

© 2017. All Rights Reserved.