Selenium與JavaScript
Selenium深入淺出之三
By 沈東良
http://blog.csdn.net/shendl/
Selenium全方位解讀--Selenium深入淺出之一
Selenium中文參考手冊--Selenium深入淺出之二
《Selenium深入淺出》一書的PDF格式的全文見 http://code.google.com/p/shendl/downloads/list
Selenium與EXT
n EXT使用JS動態產生Html和CSS代碼。
n 如果未給EXT元素指定id,會使用自增id。無法確定id的值。
n 如果EXT的介面元素髮生變化,id也會發生變化。
n Selenium錄製工具因此無法定位EXT產生的Web介面
根本原因就是Selenium需要定位html元素,而Ext的很多html元素都是Ext產生的。而且產生的元素的Id都是Ext自動建立的。
解決方案:
n Ext為每一個組件分配ID
n 但是有一些Html元素無法指定ID
n Selenium錄製工具輔助手工編寫測試代碼
n Selenium可以使用JS代碼,操作使用者介面的EXT對象。
可以使用Selenium介面的getEval方法在瀏覽器中執行JS代碼。
Selenium介面
java.lang.String getEval(java.lang.String script)
方法,動態執行JavaScript代碼。
storeEval (
script, variableName )
Arguments:
·
script - the JavaScript snippet
to run
·
variableName - the name of a variable
in which the result is to be stored.
Returns:
the results of
evaluating the snippet
結果儲存在JS的變數名中。
動態執行JavaScript代碼的注意點
通過調用Selenium介面的getEval()等方法可以直接把Java中的JavaScrip代碼發送到瀏覽器中執行。
但是,這裡實際上執行的並不是標準的JavaScript的eval()方法。getEval()方法中的JavasScript代碼的this是JavaScript中的Selenium對象,而不是window對象。
如果你需要調用當前頁面的window對象的方法,你需要直接指出window對象,如:“window.document.getElementById('foo');”。
getEval()方法中的JavasScript代碼的this是JavaScript中的Selenium對象。請注意這不是Java中的Selenium介面,而是JavaScript中的Selenium對象。JavaScript中的Selenium對象的作用是代表Java中的Selenium介面執行一系列的命令,讓瀏覽器執行。
另外,Selenium介面的selectFrame和selectWindow方法可以修改當前Selenium命令的目標視窗。也就是說,當前的window對象會改變。
Selenium執行Ext的例子:
protected Selenium browser;
……
this.browser.getEval("window.frames['1000'].window.Ext.getCmp('testId-09').setValue('應嚴辦!');");
說明:
Window是當前Selenium命令的目標視窗,這個當前視窗可以通過Selenium介面的selectFrame和selectWindow方法修改!
Selenium動態執行JavaScript的例子:
也可以使用這種方法,在Java端注入javascript代碼到頁面中動態執行,如:
rowNumStr = this.browser
.getEval("(function(){"
+ "var
tableLength=0;"
+ " var
tables=window.frames['iframe_00300000000000000003'].window.document.getElementsByTagName('table');
"
+ "for(var
j=0;j<tables.length;j++){"
+ "
if(tables[j].className=='x-grid3-row-table'){"
+ " tableLength++;"
+ "
if(tables[j].childNodes[0].childNodes[0].childNodes[1].childNodes[0].innerText=='"
+
complainIdValue + "' ) {"
+ " return tableLength;" + "
}" + "
}"
+ "}" + "return -1;" + "})();");
《Selenium深入淺出》一文到這裡就結束了。讀者通過本文應該已經能夠完全駕馭Selenium這個獨特的Web介面測試載入器一展身手了。