在web自动化测试中点击一个链接然后弹出新窗口是比较司空见惯的事情。
webdriver 中处理弹出窗口跟处理 frame 差不多,以下面的 html 代码为例
window.html
click me
下面的代码演示了如何去捕获弹出窗口
# coding:utf-8
__author__ = 'zhangzhe'
from selenium import webdriver
import time
import os
#打开Chrome
driver = webdriver.Chrome()
file_path = 'file:///' + os.path.abspath('windows.html')
driver.get(file_path)
time.sleep(3)
# 当前的window handle
ch = driver.current_window_handle
driver.find_element_by_link_text("click me").click()
time.sleep(3)
# 所有的window handles
wh = driver.window_handles
#在所有窗口中查找弹出窗口
for line in wh:
if line != ch:
driver.switch_to_window(line)
driver.find_element_by_id("kw").send_keys("selenium")
driver.switch_to_window(ch)
捕获或者说定位弹出窗口的关键在于获得弹出窗口的 handle。
在上面的代码里,current_window_handle, 然后使用了window_handles方法获取所有弹出的浏览器窗口的句柄,将这两个值的差值就是新弹出窗口的句柄。
在获取新弹出窗口的句柄后,使用 switch_to_window(line)方法,将新窗口的句柄以Name的方式作为参数传入既可捕获到新窗口了。
如果想回到以前的窗口定位元素,那么再调用1次switch_to_window方法, 传入之前窗口的句柄既可达到目的。