1

I am trying to open/close tabs with chrome as my webdriver.

driver=webdriver.Chrome()

driver.get("http://www.google.com")
driver.find_element_by_xpath('//*[@id="zV9nZe"]/div') #accepting cookies

driver.execute_script("window.open('https://google.com','_blank')") #opening a new tab
driver.switch_to.window(driver.window_handles[0]) #switching back to previous tab
driver.close() #closing previous tab

driver.switch_to(driver.current_window_handle) #switching to current tab
driver.execute_script("window.open('https://google.com','_blank')") #opening a new tab

However when I try to open a new tab after closing the previous one I get the following error NoSuchWindowException: Message: no such window: target window already closed

I tried closing or opening tabs using the following code as a workaround

driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 'w')

However both do nothing.

HouseCorgi
  • 11
  • 1

1 Answers1

0

So I think I managed to fix this issue. First of all it appears that with Chromedriver sendkeys method won't work correctly with shortcuts -see Selenium with Python: send_keys() doesn't work on headless ubuntu .

Secondly by switching to the new window using

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

Instead of

driver.switch_to(driver.current_window_handle)

seems to fix this issue. Thus the complete solution would be

driver=webdriver.Chrome()

driver.get("http://www.google.com")
driver.find_element_by_xpath('//*[@id="zV9nZe"]/div') #accepting cookies

driver.execute_script("window.open('https://google.com','_blank')") #opening a new tab
driver.switch_to.window(driver.window_handles[0]) #switching back to previous tab
driver.close() #closing previous tab

driver.switch_to.window(driver.window_handles[-1]) #switching to current tab
driver.execute_script("window.open('https://google.com','_blank')") #opening a new tab

Hope I helped some of you struggling with Selenium and tabs handling.

HouseCorgi
  • 11
  • 1