0
0
Selenium Pythontesting~10 mins

Closing browser (close vs quit) in Selenium Python - Test Execution Compared

Choose your learning style9 modes available
Test Overview

This test opens a browser, navigates to a page, opens a new tab, then closes the current tab using close() and finally quits the entire browser session using quit(). It verifies the behavior difference between close() and quit().

Test Code - Selenium
Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

def test_close_vs_quit():
    driver = webdriver.Chrome()
    driver.get('https://example.com')
    
    # Open a new tab
    driver.execute_script("window.open('https://example.com', '_blank');")
    time.sleep(1)  # Wait for tab to open
    
    # Switch to the new tab
    driver.switch_to.window(driver.window_handles[1])
    
    # Close current tab (should close the second tab)
    driver.close()
    
    # Switch back to first tab
    driver.switch_to.window(driver.window_handles[0])
    
    # Verify only one tab remains
    assert len(driver.window_handles) == 1
    
    # Quit entire browser session
    driver.quit()
Execution Trace - 9 Steps
StepActionSystem StateAssertionResult
1Test starts and Chrome browser opensBrowser window is open, no page loaded yet-PASS
2Navigate to 'https://example.com'Browser displays example.com homepage-PASS
3Execute JavaScript to open a new tab with 'https://example.com'Two tabs open, both showing example.com-PASS
4Wait 1 second for new tab to loadTwo tabs fully loaded-PASS
5Switch to the new tab (second tab)Focus on second tab showing example.com-PASS
6Close current tab (the second tab)Second tab closed, first tab remains open-PASS
7Switch to first tabFocus on first tab showing example.comVerify only one tab remains openPASS
8Assert number of open tabs is 1One tab openassert len(driver.window_handles) == 1PASS
9Quit entire browser sessionAll browser windows and tabs closed, WebDriver session ended-PASS
Failure Scenario
Failing Condition: If the test tries to switch to a tab that was already closed or if quit() is not called properly
Execution Trace Quiz - 3 Questions
Test your understanding
What does the driver.close() command do in this test?
ACloses the current browser tab only
BCloses all browser tabs and ends the session
CSwitches to the first tab
DOpens a new browser tab
Key Result
Use driver.close() to close only the current tab or window, and use driver.quit() to close all browser windows and end the WebDriver session cleanly.