selenium webdriver學習(六)-怎麼得到快顯視窗_selenium

來源:互聯網
上載者:User
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,多取了一次。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.