I am automating a workflow that opens multiple tabs through links. I need to close the current active tab once I've finished scraping its data, but I want the rest of the browser session and other tabs to remain open so I can continue my script. When I use the close() command, sometimes the driver focus seems to get lost. What is the standard process to close a tab and properly switch control back to the original window?
3 answers
The essential command for this is driver.close(), which specifically terminates the window or tab that currently has the driver's focus. However, the most critical step that many developers miss is that after closing the tab, the driver does not automatically focus on the remaining open tabs. You must explicitly tell the driver where to go using driver.switch_to.window(window_handle). A common practice is to store the "Main Window" handle at the start of your script using main_window = driver.current_window_handle. After you call driver.close() on the second tab, you immediately call driver.switch_to.window(main_window) to resume your automation. This prevents the NoSuchWindowException that often occurs if you try to interact with the browser after a tab has been closed without refocusing.
Does the driver.close() method still work the same way if the tab was opened via a JavaScript window.open() command rather than a standard HTML target link?
You should definitely avoid driver.quit(). That’s the most common mistake beginners make; quit() kills the entire driver process and all windows, while close() is strictly for the active tab.
I agree with Heather. It's a simple distinction but a vital one for complex automation. I’ve seen many automation suites fail in CI/CD because someone used quit() inside a loop. Using close() followed by a window handle switch is the only way to maintain a persistent session while cleaning up unneeded tabs as you go.
Christopher, yes, the method remains the same regardless of how the tab was opened. The key is that Selenium manages "Window Handles." Every time a new tab is opened, a new unique ID is added to driver.window_handles. Whether it's JS-triggered or a standard link, you must iterate through those handles to find the right one. I always recommend using a simple list indexing approach like driver.switch_to.window(driver.window_handles[0]) if you just want to get back to the very first tab after closing the current one.