1

So I have the first tab; the main tab. I want to open multiple tabs using selenium and once their task is done, to close them until we're back to the original first tab

url = "https://www.google.com/"
i=4
for each in reversed(range(i, 0, -1)):
    print(each)
    driver.execute_script(f"window.open('{url}');")
    driver.switch_to.window(driver.window_handles[each])
    #do stuff
    driver.close()
    driver.switch_to.window(driver.window_handles[each-1]) 

I get the following error:

selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window already closed from unknown error: web view not found

I know its something to do with the index values of each tab, where 0 would be the inital tab, correct me if I'm wrong, but I can't get it to work.# properly.

The best I could do is to get it to close each tab randomly until left with 2, then suddenly it closes both of them (no tabs left, exits browser) when reach the value of 1

Legion
  • 33
  • 1
  • 6

1 Answers1

0

your issue starts here "driver.close()" - close method closes the current window - no matter how many tabs you have, but it doesn't kill chrome instance (drive.quit() - does the job). If you want to close the current tab you can use a workaround like

# Close current tab for windows/linux
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')

# Close current tab for Mac
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 'w')
Alin Stelian
  • 861
  • 1
  • 6
  • 16