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

0 votes
How to close active/current tab without closing the browser in Selenium-Python?
Jul 23, 2019 in Selenium by Kabir
92,995 views

3 answers to this question.

0 votes

Hello Kabir, if you want to close only active tab and need to keep the browser window open, you can make use of switch_to.window method which has the input parameter as window handle-id. Following example shows how to achieve this automation:

from selenium import webdriver
import time

driver = webdriver.Firefox()
driver.get('https://www.google.com')

driver.execute_script("window.open('');")
time.sleep(5)

driver.switch_to.window(driver.window_handles[1])
driver.get("https://facebook.com")
time.sleep(5)

driver.close()
time.sleep(5)

driver.switch_to.window(driver.window_handles[0])
driver.get("https://www.yahoo.com")
time.sleep(5)

#driver.close()

You can get a better understanding with the Selenium online training.

answered Jul 24, 2019 by Abha
• 28,140 points

edited Aug 4, 2023 by Khan Sarfaraz
0 votes

You can try the following:

  1. Switch to the new opened tab.
  2. Close the current windows (in this case, the new tab).
  3. Switch back to the first window. browser.getAllWindowHandles().then(function (handles) { browser.driver.switchTo().window(handles[1]); browser.driver.close(); browser.driver.switchTo().window(handles[0]); });
For further understanding, you can refer to the Selenium Certification.
answered Dec 14, 2020 by Gitika
• 65,730 points