How to Switch Tabs in Selenium For Python

Jash Unadkat
2 min readDec 23, 2020

--

A user may have multiple tabs open while browsing the internet. In some cases, clicking on a link or a specific button opens a particular URL in a new tab. Consequently, the user may need to switch to a new tab to proceed.

To automate a test scenario in Selenium where a user switches between tabs, QAs use the current_window_handle and window_handles methods offered by Selenium WebDriver.

At a high level, the window_handles method stores the window IDs for all tabs opened in the browser. These IDs are stored in the form of a String data type.

Similarly, the window handle ID of the currently active window is stored by the current_window_handle method. For Selenium to switch to a particular window, one needs to use the switch_to_window method. Pass the window handle ID of the target tab where the user wants to switch as an argument to that method.

In order to switch tabs in Selenium-python, as shown above, follow four basic steps:

  1. Once the browser is launched and has multiple tabs active, store the window handle ID of the currently active window in a variable using the current_window_handle method
  2. Store the window handle IDs of other active tabs in a variable using the window_handles method
  3. Perform the iteration against all available window handle IDs by comparing it against the ID of the currently active tab
  4. Perform the Switch operation once the window handle ID of the desired tab is found using the switch_to.window method. Then, pass the ID of the target tab as an argument

Refer to the code below to switch tabs using selenium:

from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.get("https://accounts.google.com/signup")
driver.find_element_by_link_text("Help").click()#prints parent window title
print("Parent window title: " + driver.title)
#get current window handle
p = driver.current_window_handle
#get first child window
chwd = driver.window_handles
for w in chwd:
#switch focus to child window
if(w!=p):
driver.switch_to.window(w)
break
time.sleep(0.9)
print("Child window title: " + driver.title)
driver.quit()

On executing this code, the program will launch multiple windows. Then, the switch operation will be executed once the target ID of the tab is identified.

Run the code, automate user navigation through multiple windows, and ensure that the site works perfectly in real user conditions. This will enable the creation of a website that provides an optimal user experience.

Perform automated Selenium testing on a real device cloud for completely accurate results, everytime.

--

--

Jash Unadkat
Jash Unadkat

Written by Jash Unadkat

As a tech geek, I love writing articles about everything related to web development or software testing space.

No responses yet