-2

I want to close all other tabs except the first opened tab in Selenium. How can I do it

Apo
  • 47
  • 3
  • Does this answer your question? [Python and Selenium - Close all tabs without closing the browser](https://stackoverflow.com/questions/45141407/python-and-selenium-close-all-tabs-without-closing-the-browser) – dimay Jan 31 '22 at 08:57

1 Answers1

0

You can switch to any open tab with code like

driver.switch_to.window(driver.window_handles[1])

Where 1, 2 etc will be the tab indices. The first tab will have index 0.
So, after switching to any tab you can close that tab with

driver.close()

And then switch back to the first tab with

driver.switch_to.window(driver.window_handles[0])

You can do that in a loop / repeat this action until all unnecessary tabs are closed / only 1 tab is existing.

Prophet
  • 32,350
  • 22
  • 54
  • 79