selenium webdriver學習(六)------------如何得到快顯視窗
在selenium 1.X裡面得到快顯視窗是一件比較麻煩的事,特別是新開視窗沒有id、name的時候。當時還整理了處理了幾種方法,詳見:http://seleniumcn.cn/read.php?tid=791 。在selenium webdriver中得到新開視窗相對簡單的多,它無關新開視窗的id、name等屬性。以下面的html為例:
test.html<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;WebDriverwindow = 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;WebDriverwindow = dr.switchTo().window(handle);System.out.println("title,url = "+window.getTitle()+","+window.getCurrentUrl());}
更改原因:
迴圈裡面有兩次it.next,多取了一次。