Selenium: How to close another tab (popup)

If you open a pop-up window [1] in your Selenium tests and you want to close it, you can do this:

# Find our target window
handle = page.driver.find_window("My window title")

# Close it
page.driver.browser.switch_to.window(handle)
page.driver.browser.close

# Have the Selenium driver point to another window
last_handle = page.driver.browser.window_handles.last
page.driver.browser.switch_to.window(last_handle)

Mind these:

  • find_window returns a window handle, which is something like "{485fa8bd-fa99-4c26-9edc-97fed060036f}". If you already know your window's handle, you can skip that step.
  • The last section (switching to another window) is important as any subsequent steps will break when you are not pointing to a correct window.

[1] as in: a real browser window, maybe via window.open in JavaScript

Arne Hartherz