selenium-webdriver Interacting with the Browser Window(s) Handle multiple windows


Example

Python

Most commonly used scenario:

  1. open page in new window
  2. switch to it
  3. do something
  4. close it
  5. switch back to parent window
# Open "Google" page in parent window
driver.get("https://google.com")

driver.title # 'Google'

# Get parent window
parent_window = driver.current_window_handle 

# Open "Bing" page in child window
driver.execute_script("window.open('https://bing.com')") 

# Get list of all windows currently opened (parent + child)
all_windows = driver.window_handles 

# Get child window
child_window = [window for window in all_windows if window != parent_window][0] 

# Switch to child window
driver.switch_to.window(child_window) 

driver.title # 'Bing'

# Close child window
driver.close() 

# Switch back to parent window
driver.switch_to.window(parent_window) 

driver.title # 'Google'