【python】【selenium】python如何用selenium切换窗口

【背景】

selenium的操作都需要人为地去控制,包括如果你打开了一个新窗口,就有必要将driver重新定位到新窗口,不然元素定位都会出错。所以,切换窗口是selenium自动化程序的必备功能,建议写成公共函数方便调用。

【脚本】

def switch_window():
    windows = driver.window_handles
    driver.switch_to.window(windows[1])

上述是比较简单的一种写法,当有两个窗口时,新窗口就是windows[1]
在这个基础上,可以写成更通用的

def switch_window():
    windows = driver.window_handles
    driver.switch_to.window(windows[-1])

当然,只这么写是有缺陷的,最好加上len(windows)>=1的前提条件。

猜你喜欢

转载自blog.csdn.net/weixin_41697242/article/details/125433744
今日推荐