package com.lykion.lianxi;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class ChangeWindowTestNg {
private static WebDriver driver;
@BeforeClass
public void setUp() throws Exception{
System.setProperty("webdriver.chrome.driver", "E:\\eclipse_jar\\selenium_jar\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("file:///C:/Users/Uker/Desktop/seleniumHTML/newWindow.html");
String currentHandle = driver.getWindowHandle(); //获取当前窗口的句柄
System.out.println("当前窗口数量:" + driver.getWindowHandles().size());
Thread.sleep(1000);
}
@AfterClass
public void tearDown() throws Exception{
}
@Test
public void testCase() throws Exception{
driver.findElement(By.xpath("/html/body/form/input")).click(); //打开新的窗口
windowChange(); //调用windowChange()切换窗口
// switchToWindow("", driver); //调用switchToWindow()切换窗口
System.out.println("当前窗口数量:" + driver.getWindowHandles().size());
System.out.println("当前窗口标题:" + driver.getTitle());
WebElement element = driver.findElement(By.partialLinkText("LESS IS MORE")); //再次打开其他页面
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element);
Thread.sleep(1000);
String href = element.getAttribute("href"); //获取目标链接
((JavascriptExecutor)driver).executeScript("window.open('"+href+"')"); //打开目标链接
element.click(); //打开目标链接(另一种打开链接的方式)
windowChange(); //调用windowChange()切换窗口
// switchToWindow("new", driver); //调用switchToWindow()切换窗口;在最后一个切换窗口的时候第一个参数不能空,否则会自动切换到第一个窗口
System.out.println("当前窗口数量:" + driver.getWindowHandles().size());
System.out.println("当前窗口标题:" + driver.getTitle());
Thread.sleep(1000);
}
/**
* 封装切换窗口函数以方便调用
*/
public void windowChange() {
String currentHandle = driver.getWindowHandle(); //获取当前窗口句柄
Set allHandle = driver.getWindowHandles(); //获取所有窗口句柄
Iterator it = allHandle.iterator(); //迭代allhandle里面的句柄
while(it.hasNext()) { //用it.hasNext()判断时候有下一个窗口,如果有就切换到下一个窗口
driver.switchTo().window(it.next()); //切换到新窗口
}
}
// //封装切换窗口
// public static boolean switchToWindow(String windowTitle, WebDriver driver) {
// boolean flag = false;
// try {
// //将页面上所有的windowshandle放在如set集合当中
// String currentHandle = driver.getWindowHandle();
// Set handles = driver.getWindowHandles();
// for(String s : handles) {
// if(s.equals(currentHandle))
// continue;
// else {
// driver.switchTo().window(s);
// //和当前的窗口进行比较如果相同就切换到windowhandle
// //判断title是否和handles当前的窗口相同
// if(driver.getTitle().contains(windowTitle)) {
// flag = true;
// System.out.println("Switch to window successfully!");
// break;
// }else
// continue;
// }
// }
// } catch (Exception e) {
// // TODO: handle exception
// System.out.printf("Window cound not found!", e.fillInStackTrace());
// flag= false;
// }
// return flag;
// }
}
//获取当前窗口的句柄
System.out.println("当前窗口数量:" + driver.getWindowHandles().size());
Thread.sleep(1000);
}
@AfterClass
public void tearDown() throws Exception{
}
@Test
public void testCase() throws Exception{
driver.findElement(By.xpath("/html/body/form/input")).click(); //打开新的窗口
windowChange(); //调用windowChange()切换窗口
// switchToWindow("", driver); //调用switchToWindow()切换窗口
System.out.println("当前窗口数量:" + driver.getWindowHandles().size());
System.out.println("当前窗口标题:" + driver.getTitle());
WebElement element = driver.findElement(By.partialLinkText("LESS IS MORE")); //再次打开其他页面
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element);
Thread.sleep(1000);
String href = element.getAttribute("href"); //获取目标链接
((JavascriptExecutor)driver).executeScript("window.open('"+href+"')"); //打开目标链接
element.click(); //打开目标链接(另一种打开链接的方式)
windowChange(); //调用windowChange()切换窗口
// switchToWindow("new", driver); //调用switchToWindow()切换窗口;在最后一个切换窗口的时候第一个参数不能空,否则会自动切换到第一个窗口
System.out.println("当前窗口数量:" + driver.getWindowHandles().size());
System.out.println("当前窗口标题:" + driver.getTitle());
Thread.sleep(1000);
}
/**
* 封装切换窗口函数以方便调用
*/
public void windowChange() {
String currentHandle = driver.getWindowHandle(); //获取当前窗口句柄
Set allHandle = driver.getWindowHandles(); //获取所有窗口句柄
Iterator it = allHandle.iterator(); //迭代allhandle里面的句柄
while(it.hasNext()) { //用it.hasNext()判断时候有下一个窗口,如果有就切换到下一个窗口
driver.switchTo().window(it.next()); //切换到新窗口
}
}
// //封装切换窗口
// public static boolean switchToWindow(String windowTitle, WebDriver driver) {
// boolean flag = false;
// try {
// //将页面上所有的windowshandle放在如set集合当中
// String currentHandle = driver.getWindowHandle();
// Set handles = driver.getWindowHandles();
// for(String s : handles) {
// if(s.equals(currentHandle))
// continue;
// else {
// driver.switchTo().window(s);
// //和当前的窗口进行比较如果相同就切换到windowhandle
// //判断title是否和handles当前的窗口相同
// if(driver.getTitle().contains(windowTitle)) {
// flag = true;
// System.out.println("Switch to window successfully!");
// break;
// }else
// continue;
// }
// }
// } catch (Exception e) {
// // TODO: handle exception
// System.out.printf("Window cound not found!", e.fillInStackTrace());
// flag= false;
// }
// return flag;
// }
}
另外一种切换方式:获取所有窗口的句柄并存入set集合中,再把set集合存入list对象中,通过索引的方式切花窗口
package com.sandy;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ManyHandleChange {
private static WebDriver driver;
public static void main(String[] args) throws Exception {
// E:\eclipse_jar\selenium_jar\chromedriver_lastest\chromedriver.exe
// E:\eclipse_jar\selenium_jar\chromedriver.exe
System.setProperty("webdriver.chrome.driver", "E:\\eclipse_jar\\selenium_jar\\chromedriver_lastest\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://www.baidu.com/"); //打开百度首页
// String window_one = driver.getWindowHandle();
Thread.sleep(2000);
((JavascriptExecutor)driver).executeScript("window.open('http://www.sogou.com/')"); //用js打开新的窗口
Thread.sleep(2000);
((JavascriptExecutor)driver).executeScript("window.open('http://www.youdao.com/')"); //用js打开新的窗口
Thread.sleep(2000);
((JavascriptExecutor)driver).executeScript("window.open('http://www.qq.com/')"); //用新浪打开新的窗口
Thread.sleep(2000);
Set allWindow = driver.getWindowHandles(); //获取所有的窗口句柄
List it = new ArrayList(allWindow); //将set集合存入list对象中
System.out.println(allWindow.size()); //输出句柄集合
/**
* list集合的索引是从0开始
* 窗口在list中索引对应的窗口顺序是:第一个打开的窗口(百度)索引是0;
* 其他窗口对应的索引顺序是:最后一个打开的窗口(腾讯)索引是1,剩余的窗口索引依次是打开窗口顺序的倒序,即2是有道,3是搜狗
*/
//通过list的索引切换窗口
//切换到腾讯窗口
driver.switchTo().window(it.get(1));
String title = driver.getTitle(); //获取当前窗口的title
System.out.println("已切换到:" + title);
Thread.sleep(500);
driver.close(); //关闭当前窗口
System.out.println(title + ":已经关闭!");
Thread.sleep(1000);
//切换到有道窗口
driver.switchTo().window(it.get(2));
String title1 = driver.getTitle(); //获取当前窗口的title
System.out.println("已切换到:" + title1);
Thread.sleep(500);
driver.close(); //关闭当前窗口
System.out.println(title1 + ":已经关闭!");
Thread.sleep(1000);
//切换到搜狗窗口
driver.switchTo().window(it.get(3));
String title2 = driver.getTitle(); //获取当前窗口的title
System.out.println("已切换到:" + title2);
Thread.sleep(500);
driver.close(); //关闭当前窗口
System.out.println(title2 + ":已经关闭!");
Thread.sleep(1000);
//切换到百度窗口
driver.switchTo().window(it.get(0));
String title3 = driver.getTitle(); //获取当前窗口的title
System.out.println("已切换到:" + title3);
Thread.sleep(500);
driver.close(); //关闭当前窗口
System.out.println(title3 + ":已经关闭!");
Thread.sleep(1000);
/**
* 使用循环来实现窗口之间的相互切换、关闭
*/
// for(String i:allWindow) {
// if(i != window_one) { //判断当前是否是第一个窗口
// driver.switchTo().window(i); //如果不是,则切换到当前窗口
// System.out.println("成功切换到:" + driver.getTitle()); //为了证明确实切换了,打印一下窗口的title
// Thread.sleep(2000);
// /**
// * 截取当前窗口的图片并保存到指定文件夹中
// */
// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); //设置时间格式
// String time = dateFormat.format(Calendar.getInstance().getTime()); //获取当前时间
// File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); //执行屏幕截取
// FileUtils.copyFile(srcFile, new File("snapshot", time+".png")); //利用FileUtils工具类的copyFile()方法保存getScreenshotAs()返回的文件
// driver.close();
// }
// Thread.sleep(2000);
// }
}
}