“NoSuchWindowException: no such window: window was already closed” while switching tabs using Selenium and WebDriver through Python3

As per your question and your code trials when you intend to navigate to a new tab you need to:

  • Induce WebDriverWait while switching to the New Tab.
  • Again when you intend to switch() to the desired <iframe> you need to induce WebDriverWait again.
  • While you switch() to the desired <iframe> try to use either ID, NAME, XPATH or CSS-SELECTOR of the desired <iframe>.
  • Your own code with these simple modification will be as follows:

    from selenium import webdriver
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    
    url = "your_url"
    driver = webdriver.Chrome(executable_path = r'S:\Engineering\Jake\MasterControl Completing Pipette CalPM Forms\chromedriver')
    driver.get(url)
    windows_before  = driver.current_window_handle
    driver.find_element_by_id('portal.scheduling.prepopulate').click()
    WebDriverWait(driver, 5).until(EC.number_of_windows_to_be(2))
    windows_after = driver.window_handles
    new_window = [x for x in windows_after if x != windows_before][0]
    # driver.switch_to_window(new_window) <!---deprecated>
    driver.switch_to.window(new_window)
    WebDriverWait(driver, 5).until(EC.frame_to_be_available_and_switch_to_it((By.ID,"myframe"))) # or By.NAME, By.XPATH, By.CSS_SELECTOR
    

Leave a Comment