Introduction
The close() method is one of the most commonly used browser commands in Selenium WebDriver. It is used to close only the currently active browser window or browser tab without terminating the entire WebDriver session.
Modern web applications frequently open multiple browser windows or tabs for activities such as payment gateways, document downloads, third-party authentication, advertisements, or external links. In such situations, Selenium allows you to close only the active browser window while continuing automation in the remaining browser windows.
Unlike the quit() method, which closes every browser window and ends the WebDriver session, the close() method affects only the current browser window.
In this tutorial, you will learn what the close() method is, why it is used, its syntax, practical examples, real-world applications, common mistakes, best practices, and frequently asked interview questions.
What is close()?
The close() method is a Selenium WebDriver command that closes only the currently active browser window or browser tab.
If multiple browser windows are open, only the active window is closed, while the remaining browser windows continue to stay open and the WebDriver session remains active.
Why Do We Use close()?
The close() method is commonly used to:
Close popup windows after validation.
Close newly opened browser tabs.
Handle multiple browser windows efficiently.
Continue automation in the original browser window.
Close advertisement or external windows.
Improve browser resource management during test execution.
Syntax
driver.close()
The close() method does not accept any parameters.
Practical Example
The following example demonstrates the real-world use of the close() method.
The automation script opens a Selenium practice website, launches a new browser window, switches to it, closes only the newly opened window, returns to the original browser window, and verifies that only one browser window remains open.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
# Topic: 5. Browser Commands - close()
# Practice site: https://the-internet.herokuapp.com/windows
#
# close() closes only the current browser window. If multiple windows are open,
# the session stays alive until quit() is called.
def test_close_current_window():
driver = webdriver.Chrome()
try:
driver.get("https://the-internet.herokuapp.com/windows")
original_window = driver.current_window_handle
driver.find_element(By.LINK_TEXT, "Click Here").click()
WebDriverWait(driver, 10).until(
lambda browser: len(browser.window_handles) == 2
)
new_window = [
handle for handle in driver.window_handles
if handle != original_window
][0]
driver.switch_to.window(new_window)
driver.close()
driver.switch_to.window(original_window)
assert len(driver.window_handles) == 1
finally:
driver.quit()
Output
Second browser window opened successfully.
Second browser window closed successfully.
Control returned to the original browser window.
Only one browser window remains open.
Test Passed.
Understanding the Code
Import Required Modules
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
Imports the Selenium WebDriver along with the required classes for locating web elements and implementing explicit waits.
Launch Chrome Browser
driver = webdriver.Chrome()
Starts a new Chrome browser session.
Open the Practice Website
driver.get("https://the-internet.herokuapp.com/windows")
Opens the Selenium practice website that demonstrates handling multiple browser windows.
Store the Original Browser Window
original_window = driver.current_window_handle
Stores the handle of the original browser window so Selenium can return to it later.
Open a New Browser Window
driver.find_element(By.LINK_TEXT, "Click Here").click()
Clicks the Click Here link, which opens a second browser window.
Wait Until the New Window Opens
WebDriverWait(driver, 10).until(
lambda browser: len(browser.window_handles) == 2
)
Waits until Selenium detects that the second browser window has opened before proceeding.
Using an explicit wait makes the script more reliable and avoids synchronization issues.
Identify the New Browser Window
new_window = [
handle for handle in driver.window_handles
if handle != original_window
][0]
Retrieves the browser window handle that does not belong to the original browser window.
Switch to the New Browser Window
driver.switch_to.window(new_window)
Transfers Selenium’s control from the original browser window to the newly opened browser window.
Close the Current Browser Window
driver.close()
Closes only the currently active browser window.
Since Selenium is controlling the second browser window, only that window is closed while the original browser window remains open.
Switch Back to the Original Browser Window
driver.switch_to.window(original_window)
Returns Selenium’s control to the original browser window so that the automation can continue.
Verify Only One Browser Window Exists
assert len(driver.window_handles) == 1
Verifies that only one browser window remains after closing the second browser window.
If the condition is true, the test passes successfully.
Clean Up the Browser Session
driver.quit()
Closes the remaining browser window and ends the WebDriver session.
Here, quit() is used only for cleanup after demonstrating the close() method.
Browser Execution Flow
Launch Chrome Browser
│
▼
Open Practice Website
│
▼
Store Original Window Handle
│
▼
Click "Click Here"
│
▼
New Browser Window Opens
│
▼
Wait Until Second Window Opens
│
▼
Identify New Window
│
▼
Switch to New Window
│
▼
Close Current Window
│
▼
Switch Back to Original Window
│
▼
Verify Only One Window Exists
│
▼
End Browser Session
Automation Testing Example
Suppose you’re testing an e-commerce application.
When the customer clicks Pay Now, the payment gateway opens in a new browser window.
Your Selenium automation script can:
Open the shopping website.
Add products to the cart.
Click Checkout.
Open the payment gateway.
Validate the payment page.
Close only the payment window using
close().Return to the shopping website.
Continue with the remaining test steps.
This is one of the most common real-world uses of the close() method.
Real-World Example
Consider an online banking application.
When the user downloads an account statement, the application opens the statement in a new browser window.
The automation script can:
Log in to the banking application.
Open the statement window.
Verify the statement details.
Close only the statement window.
Return to the main banking dashboard.
Continue the remaining automation.
Common Mistakes Beginners Make
Calling close() Without Switching to the Correct Window
Incorrect
driver.close()
If Selenium is still controlling the original browser window, it may close the wrong browser window.
Correct
driver.switch_to.window(new_window)
driver.close()
Always switch to the required browser window before calling close().
Performing Operations on a Closed Window
Incorrect
driver.close()
driver.find_element(By.ID, "username")
Error
NoSuchWindowException
Once the browser window is closed, Selenium cannot perform any further operations on that window.
Forgetting to Switch Back to the Original Window
After closing the second browser window, always switch back to the original browser window before continuing the automation.
Best Practices
Use
close()only when you need to close the current browser window.Store the original browser window handle before opening additional windows.
Always switch to the correct browser window before closing it.
Switch back to the original browser window after closing the secondary window.
Verify the number of remaining browser windows whenever appropriate.
Use explicit waits while working with multiple browser windows.
Use
quit()only after the complete automation test has finished.
Conclusion
The close() method is an essential Selenium WebDriver command used to close only the currently active browser window while keeping the remaining browser windows and WebDriver session active.
It is especially useful when automating applications that open multiple browser windows or browser tabs. Understanding how to use close() with window handling techniques is an important skill for building reliable Selenium automation scripts.
Frequently Asked Questions (FAQs)
What does the close() method do?
It closes only the currently active browser window or browser tab.
Does close() terminate the WebDriver session?
No.
If other browser windows remain open, the WebDriver session continues.
When should I use close()?
Use it whenever you need to close a specific browser window without ending the complete automation session.
Can close() be used with multiple browser windows?
Yes.
It is commonly used when handling multiple browser windows or browser tabs.
What is the difference between close() and quit()?
close()closes only the active browser window.quit()closes all browser windows and terminates the WebDriver session.
Key Takeaways
The
close()method closes only the currently active browser window.The syntax is
driver.close().It is mainly used while handling multiple browser windows or tabs.
Always switch to the required browser window before calling
close().After closing a secondary window, switch back to the original browser window.
Use explicit waits to synchronize browser window handling.
close()is one of the most frequently used browser commands in Selenium automation and interviews.
