package com.sele.test;java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import com.thoughtworks.selenium.*;
import org.openqa.selenium.By;web
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import java.util.Set;chrome
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;數組
public class switchWindow {瀏覽器
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
//谷歌瀏覽器
/*
System.setProperty("webdriver.chrome.driver", "C:\\Users\\THINK\\AppData\\Local\\Google\\Chrome\\Application\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
*/
//火狐瀏覽器
// 用火狐瀏覽器
// System.setProperty("webdriver.firefox.bin","C:\\Program Files (x86)\\Mozilla Firefox\\geckodriver.exe");//增長這句,火狐32會報異常
WebDriver driver = new FirefoxDriver();
driver.get("https://www.2345.com/?k41113");//打開指定的網址
String pareWin,ziOneWin;
WebElement element = null;
pareWin = driver.getWindowHandle();//得到初始化driver時指定的窗口句柄,driver的窗口只能由driver.switchTo().window()改變
System.out.println("首頁窗口句柄"+ pareWin );
driver.findElement(By.name("word")).sendKeys("又變漂亮了!");
element = driver.findElement(By.id("j_search_sbm"));
element.click();
ziOneWin = driver.getTitle();//依然是第一個窗口的標題
System.out.println("檢索結果窗口"+ ziOneWin );
Thread.sleep(2000);
Set<String> handles = new HashSet();//初始化Set<>集合
handles = driver.getWindowHandles();
int i=0;
String strTemp = null;
for(String s : handles)//遍歷集合.這個比數組好用,簡單易讀
{
i++;
System.out.printf("第%d窗口"+s+"\n",i );
System.out.printf(pareWin+"\n" );
if(!s.contentEquals(pareWin) ) //不能用比較字符串大小那個函數,如今要比較的是兩個字符串是否相等
{
driver.switchTo().window(s);
System.out.printf("第%d窗口"+ s+"tiaoru\n",i );
System.out.println(driver.getTitle());
strTemp = s;
Thread.sleep(2000);
}
}
driver.switchTo().window(pareWin);
Thread.sleep(2000);
driver.switchTo().window(strTemp);
}函數
}firefox