Home > OS >  Python Selenium How To Close All Other Tabs Except First Tab
Python Selenium How To Close All Other Tabs Except First Tab

Time:02-01

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

CodePudding user response:

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.

  •  Tags:  
  • Related