How to close active/current tab without closing the browser in Selenium-Python?


We can close the active/current tab without closing the browser in Selenium webdriver in Python. By default, Selenium has control over the parent window. Once another browser window is opened, we have to explicitly shift the control with the help of switch_to.window method.

The handle id of the browser window where we want to shift is passed as a parameter to that method. The method window_handles returns the list of all window handle ids of the opened browsers.

The method current_window_handle is used to hold the window handle id of the browser window in focus. To close only the active or current tab we have to use the close method.

Syntax

parent = driver.window_handles[0]
chld = driver.window_handles[1]
driver.switch_to.window(chld)
driver.close()

Let us try to close active browser as shown in the below image −

Example

from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://accounts.google.com/")
#identify element
m = driver.find_element_by_link_text("Help")
m.click()
#obtain parent window handle
p= driver.window_handles[0]
#obtain browser tab window
c = driver.window_handles[1]
#switch to tab browser
driver.switch_to.window(c)
print("Page title :")
print(driver.title)
#close browser tab window
driver.close()
#switch to parent window
driver.switch_to.window(p)
print("Current page title:")
print(driver.title)
#close browser parent window
driver.quit()

Output

Updated on: 06-Apr-2021

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements