【发布时间】: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