捕获或者说定位弹出窗口的关键在于获得弹出窗口的句柄。
在代码里,使用getWindowHandle方法来获取当前浏览器窗口的句柄,使用了getWindowHandles方法获取所有弹出的浏览器窗口的句柄,然后通过排除当前句柄的方法来得到新开窗口的句柄。
在获取新弹出窗口的句柄后,使用switchto.window(newwindow_handle)方法,将新窗口的句柄作为参数传入既可捕获到新窗口了。
如果想回到以前的窗口定位元素,那么再调用1次switchto.window方法,传入之前窗口的句柄既可达到目的。
Html代码
<span style="white-space: normal; background-color: #ffffff;">test.html</span>
<html>
</html>
下面的代码演示了如何去得到弹出的新窗口
Java代码
package com.test_webdriver;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Test_popup {
public static void main(String[] args) {
String url = "file:///D:/selenium/html/popup.html";
}
}
输出结果:
title,url = 百度一下,你就知道,http://www.baidu.com/