在操作页面时,我们经常会遇到点击某个链接,弹出新的窗口,这时候需要切换到新开的窗口上进行操作,webdriver提供了相应的方法,可以实现在不同窗口之间的切换。这个方法就是switch_to.window()
首先获取当前窗口的句柄:current_window = driver.current_window_handle
当打开新的窗口之后,获取当前打开的所有窗口句柄:all_handles = driver.window_handles
通过for循环及if语句,进入新打开的窗口。代码参考:
for handle in all_handles:
if handle != current_window:
driver.switch_to.window(handle)
回到之前的窗口
for handle in all_handles:
if handle == current_window:
driver.switch_to.window(handle)