Last modified: Oct 25, 2024 By Alexander Williams

Python Selenium: close() Method

The close() method in Python Selenium is used to close the currently active browser window without terminating the entire WebDriver session.

What is the close() Method in Python Selenium?

The close() method allows you to shut the active browser window while keeping other instances open. This is different from the quit() method.

The primary difference is that quit() closes all browser windows, while close() only shuts the active one.

Why Use close() Method?

Using close() is helpful when you have multiple windows or tabs open, and you want to close a specific one without ending the WebDriver session.

This method is particularly useful in scenarios where you automate interactions with pop-up windows or multiple tabs.

How to Use close() Method

To use the close() method, make sure you have initiated a WebDriver instance. Here’s an example:


from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://example.com")

# Close the current active window
driver.close()

In this example, the browser navigates to "https://example.com", then the active window is closed using the close() method.

When to Use close() Over quit()

Use close() when you need to shut only the active window but continue using other windows or tabs. For terminating all sessions, use quit().

If you need to navigate to another page, consider using the get() Method or to navigate back, use the back() Method.

Common Scenarios with close() Method

The close() method is useful when automating interactions with multiple tabs or handling pop-up windows that need to be dismissed after an action.

It can be used alongside other navigation methods like forward() and refresh().

Related Methods

For managing browser windows and sessions, you might also explore Python Selenium: maximize_window() or learn about using Browser Profiles for custom setups.

Conclusion

The close() method in Python Selenium is a versatile tool for managing browser windows during automation. It allows precise control over which windows to close.

For detailed information, refer to the official Selenium WebDriver documentation.