How to switch to new window in Selenium for Python?


Selenium can switch to new windows when there are multiple windows opened. There may be scenarios when filling a date field in a form opens to a new window or clicking a link, button or an advertisement opens a new tab.

Selenium uses the current_window_handle and window_handles methods to work with new windows. The window_handles method contains all the window handle ids of the opened windows. The window id handles are held in the form of Set data structure [containing data type as String].

The current_window_handle method is used to store the window handle id of the present active window. Finally to switch to a particular window, switch_to_window() method is used. The handle id of the window where we want to switch is passed as an argument to that method.

The steps to be followed to implement the above concept −

  • After the application is launched, let us first store all the window handle ids in a Set data structure with the help of window_handles method.

  • We shall iterate through all the window handle ids till we get our desired window handle id.

  • Let us then grab the current window handle id with the help of current_window_handle method.

  • Then switch to that window with switch_to_window() method.

Example

Code Implementation.

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
chwnd = driver.window_handles
for w in chwnd:
   #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()

Output

Updated on: 28-Aug-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements