【问题标题】:Selenium Python does not close the child windowSelenium Python 不关闭子窗口
【发布时间】:2019-05-16 22:06:43
【问题描述】:

我的网页在点击时会打开新的浏览器窗口。我能够获得 2 个句柄,但是 driver.close() 总是关闭第一个/主窗口。

from selenium import webdriver
import time
driver = webdriver.Chrome() 
driver.get("file:///D:/blackhole/print.html")
han = driver.window_handles
print("handles:", han) # gets 1 handle
time.sleep(2)
click_btn = driver.find_element_by_link_text('Print')
click_btn.click()
han = driver.window_handles
print("handles:", han) # gets 2 handles
driver.switch_to_window = han[1] # first element is always first window handle
driver.close() # main window close

下面是调用新窗口的网页代码

<a href="print.html"  
onclick="window.open('popprint.html', 
                    'newwindow', 
                    'width=300,height=250'); 
        return false;"
>Print</a>

Firefox 也有同样的行为。 Python 3.6.7

【问题讨论】:

  • 我刚刚尝试运行其中一个测试(testShouldThrowNoSuchWindowExceptionOnAnyElementOperationIfAWindowIsClosed 在 Selenium 的 python 绑定中。测试通过了。请看一下github.com/SeleniumHQ/selenium/blob/… 因此,我觉得driver.close() 工作正常.
  • 我也在 Windows 上使用 Python 3.7.0 进行了测试。上述测试工作正常。
  • 是的。我发现它的主要区别 switch_to_window 与 switch_to.window() 。

标签: python-3.x selenium selenium-webdriver webdriverwait window-handles


【解决方案1】:

Selenium 无法关闭 活动窗口 即 新打开的窗口,因为实际上您还没有切换到 新以干净的方式打开窗口。

解决方案

关于Tab/Window切换/处理的几句话:

  • switch_to_window(window_name) 已被弃用一段时间,您需要使用 driver.switch_to.window
  • 始终跟踪 父窗口 句柄,以便稍后根据您的用例需要时返回。
  • 在选项卡/窗口之间切换之前,始终使用WebDriverWait 和expected_conditions 作为number_of_windows_to_be(num_windows)。
  • 始终跟踪子窗口句柄,以便您可以在需要时进行遍历。
  • 在提取页面标题之前,始终使用 WebDriverWait 和 expected_conditions 作为 title_contains("partial_page_title")。
  • 这是您自己的代码,上面提到了一些小的调整:

    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()
    
  • 您可以在Selenium Switch Tabs找到详细讨论

【讨论】:

  • +1 感谢 Deb 的详细回答和建议。不知何故 switch_to_window 在我的代码中没有显示弃用的警告。
  • @Nutan 逐步淘汰已弃用的方法并实施新开发的方法是每个开发人员都应遵循的最佳实践的一部分。但是,除非removed,否则不推荐使用的方法应继续按预期工作。
【解决方案2】:

driver.close() 只关闭当前窗口。 要关闭所有 Windows 并退出 webdriver,请致电 driver.quit()。

【讨论】:

  • 谢谢,虽然我只想关闭新打开的窗口。主窗口应保持打开状态。
猜你喜欢
  • 2021-03-11
  • 2017-07-24
  • 1970-01-01
  • 2012-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多