用java脚本,selenium2.0工具,切换窗口经验总结

package com.sele.test;

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;

import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import java.util.Set;

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);



}

}

posted @ 2018-03-20 17:59  满塘荷香  阅读(83)  评论(0编辑  收藏  举报