Selenium 疑問之一:WebDriver 獲得彈出窗口(轉)


捕獲或者說定位彈出窗口的關鍵在於獲得彈出窗口的句柄。
在代碼里,使用getWindowHandle方法來獲取當前瀏覽器窗口的句柄,使用了getWindowHandles方法獲取所有彈出的瀏覽器窗口的句柄,然后通過排除當前句柄的方法來得到新開窗口的句柄。
在獲取新彈出窗口的句柄后,使用switchto.window(newwindow_handle)方法,將新窗口的句柄作為參數傳入既可捕獲到新窗口了。
如果想回到以前的窗口定位元素,那么再調用1次switchto.window方法,傳入之前窗口的句柄既可達到目的。
 
HTML代碼 
1 <span style="white-space: normal; background-color: #ffffff;">test.html</span>
2 <html>
3     <head><title>Test Popup Window</title></head>
4     <body>
5         <a id = "51" href = "http://www.51.com/" target = "_blank">Let's go!</a>
6     </body>
7 </html>

 

 
 
下面的代碼演示了如何去得到彈出的新窗口
 
Java代碼
 
 1 import java.util.Iterator;
 2 import java.util.Set;
 3 
 4 import org.openqa.selenium.By;
 5 import org.openqa.selenium.WebDriver;
 6 import org.openqa.selenium.firefox.FirefoxDriver;
 7 
 8 public class PopupWindowTest {
 9         public static void main(String[] args) {
10             System.setProperty("webdriver.firefox.bin","D:\\Program Files\\Mozilla Firefox\\firefox.exe"); 
11             WebDriver dr = new FirefoxDriver();
12             String url ="\\Your\\Path\\to\\main.html";
13             dr.get(url);
14             dr.findElement(By.id("51")).click();
15 
16             //得到當前窗口的句柄
17             String currentWindow = dr.getWindowHandle();
18             //得到所有窗口的句柄
19             Set<String> handles = dr.getWindowHandles();
20 
21             Iterator<String> it = handles.iterator();
22             while(it.hasNext()){
23                 String handle = Iter.next();
24                 if(currentWindow.equals(handle)) continue;
25                 WebDriver window = dr.switchTo().window(handle);
26                 System.out.println("title,url = "+window.getTitle()+","+window.getCurrentUrl());
27             }
28         }
29 
30 }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM