How to Switch Between Windows Using Selenium Python

In this Selenium Python tutorial, we’ll learn to switch between windows. While working on a website, it is highly possible that we open a large number of windows.

Each window may require us to perform some actions for completing an end-to-end flow. For this, we should be able to switch between them.

We need to switch over the control also and then do the required operation, because, by default, the focus remains on the parent window.

Switch Between Windows Using Selenium Python

Switch Between Windows Selenium Python

Switch Between Windows: Selenium Python

WebDriver supports moving between these windows using the “switch_to_window()” method.

driver.switch_to_window("window_handle")

Webdriver will now interpret all calls to the driver to be coming from the above window.

Let’s see an example code to understand how it works.

from selenium import webdriver
 from selenium.webdriver.common.keys import Keys
 from selenium.webdriver.common.by import By
 import time

#open the first window
 driver = webdriver.Firefox()
 driver.maximize_window()
 driver.get("http://www.facebook.com")

#get the window handle after the window has opened
 window_before = driver.window_handles[0]

window_before_title = driver.title
 print(window_before_title)

#open a new window
 driver.execute_script("window.open('http://www.twitter.com', 'new window')")

#get the window handle after a new window has opened
 window_after = driver.window_handles[1]

#switch on to new child window
 driver.switch_to.window(window_after)
 time.sleep(10)

window_after_title = driver.title
 print(window_after_title)

#Compare and verify that main window and child window title don't match
 if window_before_title != window_after_title:
 print('Context switched to Twitter, so the title did not match')
 else:
 print('Control did not switch to new window')

#switch back to original window
 driver.switch_to.window(window_before)

#Verify that the title now match
 if window_before_title == driver.title:
 print('Context returned to parent window. Title now match')

print(driver.title)

In the above scenario, we are moving from Facebook to Twitter. After that, we are moving the context also from Facebook to Twitt, using “switch_to.window()” command.

Next, we compared the title of the two web pages to verify that it has now changed as the context has moved to Twitter.

In the end, the context gets transferred to Facebook, and now we verify that title now match.

Quick wrap up – Switch Between Windows

It is essential to understand how to use Selenium Python to switch between windows. You can re-use this technique to solve real-time use cases in your projects.

For more updates on Selenium Python tutorials, do follow our social media (Facebook/Twitter) accounts.

Best,

TechBeamers