Switch To Windows

Example site: https://demo.automationtesting.in/Windows.html

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

driver.get("https://demo.automationtesting.in/Windows.html")

# Get the handle of the main window
main_window_handle = driver.current_window_handle
print("Main window handle:", main_window_handle)

driver.find_element(By.CLASS_NAME, 'btn-info').click()

# Get all window handles
all_window_handles = driver.window_handles
print("All window handles:", all_window_handles)

# Switch to other windows and perform actions
for handle in all_window_handles:
    if handle != main_window_handle:
        driver.switch_to.window(handle)
        # Perform actions in the new window/tab
        print("Switched to window:", handle)
        # Example: get title of the current window
        print("Current window title:", driver.title)
        # Close the current window
        driver.close()
        # Optionally, switch back to the main window
        driver.switch_to.window(main_window_handle)

driver.quit()

'''
OUTPUT
Main window handle: 8A82E3C16B7277BF422E1D8C24EA9C5E
All window handles: ['8A82E3C16B7277BF422E1D8C24EA9C5E', 'A50EAA220A4371A61CF1461666261C1F']
Switched to window: A50EAA220A4371A61CF1461666261C1F
Current window title: Selenium
'''

Optionally, we can use index to switch to other windows too.

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

driver.get("https://demo.automationtesting.in/Windows.html")

# Get the handle of the main window
main_window_handle = driver.current_window_handle
print("Main window handle:", main_window_handle)

driver.find_element(By.CLASS_NAME, 'btn-info').click()

# Get all window handles
all_window_handles = driver.window_handles
print("All window handles:", all_window_handles)

# use index to switch to another window
for i in range(len(all_window_handles)):
    driver.switch_to.window(all_window_handles[i])
    print(driver.title)

# Quit the browser
driver.quit()

'''
OUTPUT
Main window handle: 9EFA4E01918AE098729558BD3013577F
All window handles: ['9EFA4E01918AE098729558BD3013577F', '638C68C3D3459C90561C1DB2EF9589B8']
Frames & windows
Selenium
'''
Updated on