分享

WebDriver 获得弹出窗口和切换回原窗口

 小猪窝969 2015-10-14
捕获或者说定位弹出窗口的关键在于获得弹出窗口的句柄。

在代码里,使用getWindowHandle方法来获取当前浏览器窗口的句柄,使用了getWindowHandles方法获取所有弹出的浏览器窗口的句柄,然后通过排除当前句柄的方法来得到新开窗口的句柄。

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

如果想回到以前的窗口定位元素,那么再调用1次switchto.window方法,传入之前窗口的句柄既可达到目的。

Java代码

 package com.test;
import java.util.Iterator;
import java.util.Set;
import java.util.zip.Inflater;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class Testwww {
 static WebDriver dr;
  @Test
  public void search() {
   dr = new FirefoxDriver();
   dr.get("http://xxxxxx/");
   dr.findElement(By.name("username")).clear();
   dr.findElement(By.name("username")).sendKeys("xxxxx");
   dr.findElement(By.name("password")).clear();
   dr.findElement(By.name("password")).sendKeys("xxxx");
   dr.findElement(By.xpath("//input[@class='btn btn-primary']")).click();
   dr.findElement(By.xpath("//*[@id='syscotent']/div[26]/div/a[1]/img")).click();
   //得到当前窗口的句柄
   String currentWindow = dr.getWindowHandle();
   //得到所有窗口的句柄,set方法可以方便地将需要的类型,以集合类型保存在一个变量中,Set是一个不包含重复元素的collection
   Set<String> handles = dr.getWindowHandles();
   Iterator<String> it = handles.iterator();
   //hasNext检查序列中是否还有元素
   while(it.hasNext()){
    //第一次调用Iterator的next()方法时,它返回序列的第一个元素,使用next()获得序列中的下一个元素
    String handle = it.next();
    if (currentWindow.equals(handle)) continue;
    WebDriver window = dr.switchTo().window(handle);
    dr.findElement(By.xpath("//*[@id='searchform']/table/tbody/tr[1]/td[1]/input")).click();
   
   }
  
   dr.switchTo().window(currentWindow);
   dr.findElement(By.xpath(".//*[@id='syscotent']/div[2]/div/a[1]/img")).click();
  }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多