如果遇到点击按钮或链接后出现新窗口的情况,就需要使用窗口切换的方法。
本例中就是先打开百度搜索界面,然后利用js打开一个百度新闻界面,然后通过selenium提供的窗口切换方法切换窗口
1 package com.test.windows; 2 3 import java.util.Iterator; 4 import java.util.Set; 5 6 import org.openqa.selenium.By; 7 import org.openqa.selenium.JavascriptExecutor; 8 import org.openqa.selenium.WebDriver; 9 import org.openqa.selenium.firefox.FirefoxDriver; 10 11 public class WindowsSwitch { 12 13 public static void main(String[] args) { 14 15 WebDriver driver = new FirefoxDriver(); 16 driver.get("http://www.baidu.com"); 17 driver.manage().window().maximize(); 18 19 String searchHandle = driver.getWindowHandle(); 20 System.out.println("baidu search handle : " + searchHandle); 21 22 // 获取百度新闻的连接,然后利用js打开一个新的窗口 23 waitTime(3000); 24 String href = driver.findElement(By.cssSelector("[name=tj_trnews]")).getAttribute("href"); 25 System.out.println("the link of news is : " + href); 26 JavascriptExecutor executor = (JavascriptExecutor) driver; 27 executor.executeScript("window.open(‘" + href + "‘)"); 28 29 waitTime(3000); 30 Set<String> handles = driver.getWindowHandles(); 31 Iterator iterator = handles.iterator(); 32 Iterator iterator2 = handles.iterator(); 33 34 // 进入百度新闻窗口,并获取title验证 35 waitTime(3000); 36 while (iterator.hasNext()) { 37 String h = (String) iterator.next(); 38 if (h != searchHandle) { 39 driver.switchTo().window(h); 40 if (driver.getTitle().contains("百度新闻")) { 41 System.out.println("switch to news page successfully"); 42 break; 43 } else { 44 continue; 45 } 46 } 47 48 } 49 50 // 返回百度首页 51 waitTime(3000); 52 /* 53 * 可以直接使用searchHandle来切换,也可以利用遍历来切换 54 * driver.switchTo().window(searchHandle); 55 * if(driver.getTitle().contains("百度一下")){ 56 * System.out.println("switch to search page successfully"); 57 * driver.findElement(By.cssSelector("#kw")).sendKeys( 58 * "switch successfully"); } 59 */ 60 while (iterator2.hasNext()) { 61 String h = (String) iterator2.next(); 62 if (searchHandle.equals(h)) { 63 driver.switchTo().window(h); 64 if (driver.getTitle().contains("百度一下")) { 65 System.out.println("switch to search page successfully"); 66 driver.findElement(By.cssSelector("#kw")).sendKeys("switch successfully"); 67 break; 68 } else { 69 continue; 70 } 71 } 72 73 } 74 75 waitTime(3000); 76 driver.quit(); 77 78 } 79 80 static public void waitTime(int time) { 81 82 try { 83 Thread.sleep(time); 84 } catch (InterruptedException e) { 85 // TODO Auto-generated catch block 86 e.printStackTrace(); 87 } 88 } 89 90 }
运行结果:
baidu search handle : {57536d1e-6817-4127-83d6-6eb138f28e51}
the link of news is : http://news.baidu.com/
switch to news page successfully
switch to search page successfully
时间: 2024-10-10 10:05:50