捕获或者说定位弹出窗口的关键在于获得弹出窗口的句柄。 在代码里,使用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(); } } |
|
来自: 小猪窝969 > 《selenium-java》