在selenium 1.X里面得到彈出窗口是一件比較麻煩的事,特別是新開窗口沒有id、name的時候。當時還整理了處理了幾種方法,詳見:http://seleniumcn.cn/read.php?tid=791 。在selenium webdriver中得到新開窗口相對簡單的多,它無關新開窗口的id、name等屬性。以下面的html為例:
- <span style="white-space: normal; #ffffff;">test.html</span>
- <html>
- <head><title>Test Popup Window</title></head>
- <body>
- <a id = "51" href = "http://www.51.com/" target = "_blank">Let's go!</a>
- </body>
- </html>
下面的代碼演示了如何去得到彈出的新窗口
- import java.util.Iterator;
- import java.util.Set;
- import org.openqa.selenium.By;
- import org.openqa.selenium.WebDriver;
- import org.openqa.selenium.firefox.FirefoxDriver;
- public class PopupWindowTest {
- /**
- * @author gongjf
- */
- public static void main(String[] args) {
- System.setProperty("webdriver.firefox.bin","D:\\Program Files\\Mozilla Firefox\\firefox.exe");
- WebDriver dr = new FirefoxDriver();
- String url ="\\Your\\Path\\to\\main.html";
- dr.get(url);
- dr.findElement(By.id("51")).click();
- //得到當前窗口的句柄
- String currentWindow = dr.getWindowHandle();
- //得到所有窗口的句柄
- Set<String> handles = dr.getWindowHandles();
- Iterator<String> it = handles.iterator();
- while(it.hasNext()){
- String handle = it.next();
- if(currentWindow.equals(handle)) continue;
- WebDriver window = dr.switchTo().window(handle);
- System.out.println("title,url = "+window.getTitle()+","+window.getCurrentUrl());
- }
- }
- }
輸出結果:
- title,url = 51.com 真人配對玩游戲,http://www.51.com/
捕獲或者說定位彈出窗口的關鍵在於獲得彈出窗口的句柄。(句柄,我的理解是瀏覽器窗口的一個唯一標識,記得以前玩"按鍵精靈"也有這玩樣。)
在上面的代碼里,使用windowhandle方法來獲取當前瀏覽器窗口的句柄,使用了windowhandles方法獲取所有彈出的瀏覽器窗口的句柄,然后通過排除當前句柄的方法來得到新開窗口的句柄。
在獲取新彈出窗口的句柄后,使用switchto.window(newwindow_handle)方法,將新窗口的句柄作為參數傳入既可捕獲到新窗口了。
如果想回到以前的窗口定位元素,那么再調用1次switch_to.window方法,傳入之前窗口的句柄既可達到目的。
----------------------------------------------------------2102年6月20日------------------------------------------------------
PS:今天發現while里的代碼有些問題。由原來的:
- while(it.hasNext()){
- if(currentWindow == it.next()) continue;
- WebDriver window = dr.switchTo().window(it.next());
- System.out.println("title,url = "+window.getTitle()+","+window.getCurrentUrl());
- }
更改為:
- while(it.hasNext()){
- String handle = it.next();
- if(currentWindow.equals(handle)) continue;
- WebDriver window = dr.switchTo().window(handle);
- System.out.println("title,url = "+window.getTitle()+","+window.getCurrentUrl());
- }
更改原因:
循環里面有兩次it.next,多取了一次。

