selenium webdriver 如何得到彈出窗口

在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,多取了一次。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容