在日常的 WebUI 自动化测试脚本执行的过程中,经常会打开不同的网页,进行相应的操作,此时可能会打开很多的网页,当打开的网页过多时,无效的网页资源对运行脚本的机器造成了过多无效的资源浪费,因而在日常的网页自动化测试脚本运行的过程中要关闭过多冗余的页面,降低系统无效损耗。
此文中所述方法通过 URL 对已开窗口进行匹配,将不匹配的窗口页面关闭,一定程度减少了系统损耗,有兴趣的小主们,可进一步优化相应的程序源码,或在日常脚本编写调用此方法的过程中尽量使参数 URL 足够精确,可最大限度的减少系统无效损耗。
多不闲聊,小二上码。。。敬请各位小主参阅,希望能对您在日常的 WebUI 自动化脚本编写有一定的启发和帮助。若有不足或错误之处,敬请大神指正,不胜感激!
1
/**
2
* close the window if current URL is not expected, and get expected URL
3
*
4
*
@author
Aaron.ffp
5
*
@version
V1.0.0: autoSeleniumDemo main.aaron.sele.core SeleniumCore.java getUrl, 2015-6-22 12:22:30 Exp $
6
*
7
*
@param
url : expected URL
8
*
@return
WebDriver
9
*/
10
public
WebDriver getUrl(String url){
11
//
define variable to store current page title
12
String currentUrl = ""
;
13
14
//
get all windows
15
Set<String> windows =
this
.webdriver.getWindowHandles();
16
17
if
(windows.size() < 1
) {
18
return
this
.webdriver;
19
}
20
21
try
{
22
for
(String window : windows) {
23
//
change window
24
this
.webdriver.switchTo().window(window);
25
26
//
refresh the page. you can annotation this, because it's not necessary when network is good
27
//
this.webdriver.navigate().refresh();
28
29
Thread.sleep(3000
);
30
31
//
get page url
32
currentUrl =
this
.webdriver.getCurrentUrl().toString();
33
34
//
verify the current page is expect or not, return this if correct
35
if
(!
currentUrl.startsWith(url)) {
36
this
.webdriver.close();
37
}
38
}
39
}
catch
(Exception e) {
40
e.printStackTrace();
41
}
finally
{
42
this
.webdriver.get(url);
43
}
44
45
return
this
.webdriver;
46
}
至此, WebUI 自动化功能测试脚本 第 013-通过 URL 关闭多余的已开浏览器窗口 顺利完结,希望此文能够给初学 Selenium 的您一份参考。
最后,非常感谢亲的驻足,希望此文能对亲有所帮助。热烈欢迎亲一起探讨,共同进步。非常感谢! ^_^

