Home > Back-end >  Closing tab in selenium is making current_window_handle = NoneType, even when there is another tab o
Closing tab in selenium is making current_window_handle = NoneType, even when there is another tab o

Time:09-21

As the title says, I'm having an issue where I have two tabs opened, trying to close all but 1 of them, and as soon as I close a tab, the current_window_handle value gets deleted. However, I do notice there is still my window handle in the window_handles list. Wondering if anyone else has encountered this issue as well.

The code in question:

from selenium import webdriver

browser = webdriver.Chrome()
browser.get('http://example.com')
browser.execute_script("window.open('');")
window_id = browser.window_handles[-1]
browser.switch_to.window(window_id)
browser.close()
browser.get('https://google.ca')
selenium.common.exceptions.NoSuchWindowException: Message: no such window: target window already closed
selenium==3.141.0
chrome=93.0.4577.63
ChromeDriver=93.0.4577.63

CodePudding user response:

Fixed the issue. Just add

window_id = browser.window_handles[0]
browser.switch_to.window(window_id)

to reset the current_window_handle property.

So now the code is

from selenium import webdriver

browser = webdriver.Chrome()
browser.get('http://example.com')
browser.execute_script("window.open('');")
window_id = browser.window_handles[-1]
browser.switch_to.window(window_id)
browser.close()
window_id = browser.window_handles[0]
browser.switch_to.window(window_id)
browser.get('https://google.ca')
  • Related