selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window…
- User
selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window already closed
- Assistant
This exception is raised when the driver attempts to switch to a window that has already been closed. It usually occurs when the driver is trying to interact with a browser window or tab that was closed while the driver was still working on it.
To resolve this issue, you can try the following:
-
Check for any code that closes windows or tabs prematurely and modify it accordingly.
-
Use the
driver.window_handlesattribute to get a list of all open windows or tabs and ensure that the target window is still open before trying to switch to it. -
Catch the exception and handle it accordingly, for example by refreshing the page or opening a new window and trying again.
Here is an example code snippet that catches the exception and retries the window switch:
import time from selenium import webdriver driver = webdriver.Chrome() # navigate to a webpage that opens a new window driver.get("https://www.google.com") driver.find_element_by_link_text("Gmail").click() # switch to the new window try: new_window = driver.window_handles[1] driver.switch_to.window(new_window) except NoSuchWindowException: print("Window closed, retrying...") time.sleep(1) new_window = driver.window_handles[1] driver.switch_to.window(new_window) # do some work in the new window print(driver.current_url) # close the new window and switch back to the original window driver.close() driver.switch_to.window(driver.window_handles[0]) # do some work in the original window print(driver.current_url) driver.quit() -