Selenium Python does not close the child window

◇◆丶佛笑我妖孽 提交于 2019-12-06 14:10:50

Selenium is unable to close the active window i.e the newly opened window because practically you havn't switched to the newly opened window in a clean way.

Solution

A few words about Tab/Window switching/handling:

  • switch_to_window(window_name) is deprecated for quite some time now and you need to use driver.switch_to.window
  • Always keep track of the Parent Window handle so you can traverse back later if required as per your usecase.
  • Always use WebDriverWait with expected_conditions as number_of_windows_to_be(num_windows) before switching between Tabs/Windows.
  • Always keep track of the Child Window handles so you can traverse whenever required.
  • Always use WebDriverWait with expected_conditions as title_contains("partial_page_title") before extracting the Page Title.
  • Here is your own code with some minor tweaks mentioned above:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    driver = webdriver.Firefox(executable_path=r'C:\WebDrivers\geckodriver.exe')
    driver.get("file:///D:/blackhole/print.html")
    parent_han  = driver.window_handles
    driver.find_element_by_link_text('Print').click()
    WebDriverWait(driver, 10).until(EC.number_of_windows_to_be(2))
    all_han = driver.window_handles
    new_han = [x for x in all_han if x != parent_han][0]
    driver.switch_to.window(new_han)
    driver.close()
    
  • You can find a detailed discussion in Selenium Switch Tabs

driver.close() only closes the current window. To close all Windows and quit the webdriver, call driver.quit() instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!