1.通过浏览器的句柄来操纵窗口,得到句柄的方法
|
1
2
3
4 |
public String getWindowHandle(){ String currentWindow = driver.getWindowHandle(); return
currentWindow;} |
2.切换到最新的窗口
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14 |
public void switchToNewWindow(){ //得到当前句柄String currentWindow = driver.getWindowHandle(); //得到所有窗口的句柄 Set<String> handles = driver.getWindowHandles(); //排除当前窗口的句柄,则剩下是新窗口 Iterator<String> it = handles.iterator(); while(it.hasNext()){ if(currentWindow == it.next()) continue; driver.switchTo().window(it.next()); } } |
3.切换到特定的窗口
|
1
2
3 |
public void switchToOneWindow(String windowHandle){ driver.switchTo().window(windowHandle);} |
4.举例:
打开页面A,点击A页面的链接在新窗口打开页面B,验证B页面后关闭之,转回到A页面
|
1
2
3
4
5
6
7
8
9
10
11
12 |
open("URLA");//打开页面A String w1 = getWindowHandle(); //得到页面A的句柄assertTrue(isElementPresent("//*[contains(.,‘欢迎来到‘)]"),"首页打开失败"); //校验A页面元素stepInfo("3.点击链接");clickByLink("URLB");switchToNewWindow();//切换到页面BassertTrue(isElementPresent("//*[contains(.,‘您好,欢迎来到‘)]"),"打开失败");close();//关闭页面BswitchToOneWindow(w1); //返回A |
注:上面的open, clickByLink, close都是封装了webDriver操作的方法,比较简单的
|
1
2
3
4
5
6
7
8
9
10
11
12 |
public void open(String url){ driver.get(url);}public void clickByLink(String text){ driver.findElement(By.linkText(text)).click();}public
void close(){ driver.close();} |
欢迎光临娇娇家的美衣阁 http://shop105984718.taobao.com/
原文地址:http://www.cnblogs.com/joewu/p/3718721.html