在selenium 1.X里面得到彈出窗口是一件比較麻煩的事,特別是新開窗口沒有id、name的時(shí)候。當(dāng)時(shí)還整理了處理了幾種方法,詳見:http://seleniumcn.cn/read.php?tid=791 。在selenium webdriver中得到新開窗口相對(duì)簡單的多,它無關(guān)新開窗口的id、name等屬性。以下面的html為例:
<span style="white-space: normal; background-color: #ffffff;">test.html</span>
<html>
<head><title>Test Popup Window</title></head>
<body>
<a id = "51" 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();
//得到當(dāng)前窗口的句柄
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 真人配對(duì)玩游戲,http://www.51.com/
捕獲或者說定位彈出窗口的關(guān)鍵在于獲得彈出窗口的句柄。(句柄,我的理解是瀏覽器窗口的一個(gè)唯一標(biāo)識(shí),記得以前玩"按鍵精靈"也有這玩樣。)
在上面的代碼里,使用windowhandle方法來獲取當(dāng)前瀏覽器窗口的句柄,使用了windowhandles方法獲取所有彈出的瀏覽器窗口的句柄,然后通過排除當(dāng)前句柄的方法來得到新開窗口的句柄。
在獲取新彈出窗口的句柄后,使用switchto.window(newwindow_handle)方法,將新窗口的句柄作為參數(shù)傳入既可捕獲到新窗口了。
如果想回到以前的窗口定位元素,那么再調(diào)用1次switch_to.window方法,傳入之前窗口的句柄既可達(dá)到目的。
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());
}
更改原因:
循環(huán)里面有兩次it.next,多取了一次。