webdirver学习--怎样得到弹出窗口

来源:互联网 发布:怎样填写淘宝店铺简介 编辑:程序博客网 时间:2024/05/11 16:40

简单写一个待测试的页面,如下:


   <span style="white-space: normal; background-color: rgb(255, 255, 255); ">test.html</span>                  <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>  


测试代码如下:

package com.jc.test4;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 {           public static void main(String[] args) {          //System.setProperty("webdriver.firefox.bin","D:\\Program Files\\Mozilla Firefox\\firefox.exe");            WebDriver dr = new FirefoxDriver();          String url ="E:\\test.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|51游戏_好玩的游戏社区化平台_游戏|交友|空间尽在51.com,http://www.51.com/。


    捕获或者说定位弹出窗口的关键在于获得弹出窗口的句柄。(句柄,可以简单理解为浏览器窗口的一个唯一标识。)

在上面的代码里,使用windowhandle方法来获取当前浏览器窗口的句柄,使用了windowhandles方法获取所有弹出

的浏览器窗口的句柄,然后通过排除当前句柄的方法来得到新开窗口的句柄。

    在获取新弹出窗口的句柄后,使用switchto.window(newwindow_handle)方法,将新窗口的句柄作为参数传入既可

捕获到新窗口了。如果想回到以前的窗口定位元素,那么再调用1次switch_to.window方法,传入之前窗口的句柄

既可达到目的。


0 0
原创粉丝点击