selenium测试(Java)--关闭窗口(二十)
Posted qingxin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了selenium测试(Java)--关闭窗口(二十)相关的知识,希望对你有一定的参考价值。
quit方法:退出相关的驱动程序和关闭所有窗口
close方法:关闭当前窗口
package com.test.closewindow; 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.firefox.FirefoxDriver; public class WindowsClose { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); driver.get("http://www.baidu.com"); driver.manage().window().maximize(); String searchHandle = driver.getWindowHandle(); String newsHandle = null; System.out.println("baidu search handle : " + searchHandle); // 获取百度新闻的连接,然后利用js打开一个新的窗口 waitTime(3000); String href = driver.findElement(By.cssSelector("[name=tj_trnews]")).getAttribute("href"); System.out.println("the link of news is : " + href); JavascriptExecutor executor = (JavascriptExecutor) driver; executor.executeScript("window.open(‘" + href + "‘)"); waitTime(3000); Set<String> handles = driver.getWindowHandles(); Iterator iterator = handles.iterator(); Iterator iterator2 = handles.iterator(); // 进入百度新闻窗口,并获取title验证 waitTime(3000); while (iterator.hasNext()) { String h = (String) iterator.next(); if (h != searchHandle) { driver.switchTo().window(h); if (driver.getTitle().contains("百度新闻")) { System.out.println("switch to news page successfully"); newsHandle = driver.getWindowHandle(); break; } else { continue; } } } // 返回百度首页 waitTime(3000); /* * 可以直接使用searchHandle来切换,也可以利用遍历来切换 * driver.switchTo().window(searchHandle); * if(driver.getTitle().contains("百度一下")){ * System.out.println("switch to search page successfully"); * driver.findElement(By.cssSelector("#kw")).sendKeys( * "switch successfully"); } */ while (iterator2.hasNext()) { String h = (String) iterator2.next(); if (searchHandle.equals(h)) { driver.switchTo().window(h); if (driver.getTitle().contains("百度一下")) { System.out.println("switch to search page successfully"); driver.findElement(By.cssSelector("#kw")).sendKeys("switch successfully"); driver.close();// 只关闭百度首页 System.out.println("close search page successfully"); driver.switchTo().window(newsHandle);// 切换到百度新闻 System.out.println("当前的title是: " + driver.getTitle());// 获取title waitTime(3000); break; } else { continue; } } } waitTime(3000); driver.quit(); } static public void waitTime(int time) { try { Thread.sleep(time); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
执行结果:
baidu search handle : {75749f9a-f6b7-4fe6-80ae-dd9e053dd577}
the link of news is : http://news.baidu.com/
switch to news page successfully
switch to search page successfully
close search page successfully
当前的title是: 百度新闻搜索——全球最大的中文新闻平台
以上是关于selenium测试(Java)--关闭窗口(二十)的主要内容,如果未能解决你的问题,请参考以下文章
Java+Selenium 如何实现关闭当前窗口并返回上一个窗口-driver.close()
《手把手教你》系列技巧篇(二十六)-java+ selenium自动化测试-浏览器操作(详细教程)
selenium自动化测试入门 Alert/Confirm/Prompt 弹出窗口处理