robotium原理之獲取WebElement元素

robotium框架支持WebView,在robotium中有getWebElements()、getWebElements(By by)等方法來獲取android中的WebView的元素,並提供了 clickOnWebElement方法來完成點擊事件.android中的原生控件是比較好攻取的,那麼對於WebView這個框架是怎麼獲取的呢。javascript

第一步:利用JS獲取頁面中的全部元素 html

         在PC上,獲取網頁的元素能夠經過注入javascript元素來完成,以Chrome瀏覽器爲例,打開工具——JavaScript控制檯(快捷方式:Ctrl+Shift+J),輸入 javascript:prompt(document.URL)即會彈出含當前頁面的URL的提示框,所以經過編寫適當的JS腳本是能夠在這個彈出框中顯示全部頁面元素的。RobotiumWeb.js就是此功能實現用的JS腳本。以solo中getWebElements()爲例,java

[java] view plaincopy在CODE上查看代碼片派生到個人代碼片android

  1. public ArrayList<WebElement> getWebElements(boolean onlySufficientlyVisible){  web

  2.     boolean javaScriptWasExecuted = executeJavaScriptFunction("allWebElements();");  瀏覽器

  3.       

  4.     return getWebElements(javaScriptWasExecuted, onlySufficientlyVisible);  app

  5. }  框架

[java] view plaincopy在CODE上查看代碼片派生到個人代碼片ide

  1. private boolean executeJavaScriptFunction(final String function){  函數

  2.     final WebView webView = viewFetcher.getFreshestView(viewFetcher.getCurrentViews(WebView.classtrue));  

  3.   

  4.     if(webView == null){  

  5.         return false;  

  6.     }  

  7.                //作一些JS注入執行前的準備工做,例如將WebView設爲可容許執行JS等,並將RobotiumWeb.js中的腳本以String形式返回  

  8.     final String javaScript = prepareForStartOfJavascriptExecution();  

  9.   

  10.     activityUtils.getCurrentActivity(false).runOnUiThread(new Runnable() {  

  11.         public void run() {  

  12.             if(webView != null){  

  13.                 webView.loadUrl("javascript:" + javaScript + function);  

  14.             }  

  15.         }  

  16.     });  

  17.     return true;  

  18. }  

        能夠看出這個方法執行的是allWebElements();函數,即相似執行RobotiumWeb.js文件中以下JS代碼片斷:

能夠把以下片斷放到JavaScript控制檯中看效果

[javascript] view plaincopy在CODE上查看代碼片派生到個人代碼片

  1. javascript:  

  2. function allWebElements() {  

  3.     for (var key in document.all){  

  4.         try{  

  5.             promptElement(document.all[key]);   //調用promptElement(element)函數          

  6.         }catch(ignored){}  

  7.     }  

  8.     finished();    //執行完後,調用finished()函數  

  9. }  

  10.   

  11. function promptElement(element) {  

  12.     var id = element.id;  

  13.     var text = element.innerText;  

  14.     if(text.trim().length == 0){  

  15.         text = element.value;  

  16.     }  

  17.     var name = element.getAttribute('name');  

  18.     var className = element.className;  

  19.     var tagName = element.tagName;  

  20.     var attributes = "";  

  21.     var htmlAttributes = element.attributes;  

  22.     for (var i = 0, htmlAttribute; htmlAttribute = htmlAttributes[i]; i++){  

  23.         attributes += htmlAttribute.name + "::" + htmlAttribute.value;  

  24.         if (i + 1 < htmlAttributes.length) {  

  25.             attributes += "#$";  

  26.         }  

  27.     }  

  28.   

  29.     var rect = element.getBoundingClientRect();  

  30.     if(rect.width > 0 && rect.height > 0 && rect.left >= 0 && rect.top >= 0){  

  31.         prompt(id + ';,' + text + ';,' + name + ";," + className + ";," + tagName + ";," + rect.left + ';,' + rect.top + ';,' + rect.width + ';,' + rect.height + ';,' + attributes);   //彈出包含id、text、name等字段的提示框  

  32.     }  

  33. }  

  34. function finished(){  

  35.     prompt('robotium-finished');    //彈出包含robotium-finished字符串的提示框,用於標識腳本注入執行結束  

  36. }  


        從腳本中能夠看出JS得到頁面元素後還進行了必定的格式化處理,在每一個元素之間加了;,符號,這也是爲了在後面代碼中更加方便地解析。腳本的最後調用了finished()函數,即彈出包含robotium-finished的提示框。這一步完成了頁面元素的獲取,那麼提示框中包含的內容在Android中怎麼獲取呢?

第二步:在Android中獲取WebView中prompt提示框中的信息

        在Android的Webkit包中有個WebChromeClient類,這個類中的onJsPrompt方法就是用於處理WebView中的提示框的,當WebView中有JS提示框時,會回調該方法,String message參數將包含提示框中的信息,所以robotium寫了個繼承自WebChromeClient類的RobotiumWebClient類。覆寫了onJsPrompt

onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result)

[java] view plaincopy在CODE上查看代碼片派生到個人代碼片

  1. @Override  

  2. public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult r) {  

  3.   

  4.     if(message != null && (message.contains(";,") || message.contains("robotium-finished"))){  

  5.                        //若是提示框中包含robotium-finished字符串,即表示那段JS注入腳本執行完畢了  

  6.         if(message.equals("robotium-finished")){  

  7.             webElementCreator.setFinished(true);  

  8.         }  

  9.         else{  

  10.             webElementCreator.createWebElementAndAddInList(message, view);//有人提示框中的內容,那麼就能夠對提示框中的內容進行處理了  

  11.         }  

  12.         r.confirm();  

  13.         return true;  

  14.     }  

  15.     else {  

  16.         if(originalWebChromeClient != null) {  

  17.             return originalWebChromeClient.onJsPrompt(view, url, message, defaultValue, r);   

  18.         }  

  19.         return true;  

  20.     }  

  21.   

  22. }  

      

     另外,本來的WebView默認是不容許執行JS的,所以須要先執行enableJavascriptAndSetRobotiumWebClient方法。將JavaScriptEnabled設置爲true,將將WebChromeClient設置爲robotiumWebClient

[java] view plaincopy在CODE上查看代碼片派生到個人代碼片

  1. public void enableJavascriptAndSetRobotiumWebClient(List<WebView> webViews, WebChromeClient originalWebChromeClient){  

  2.     this.originalWebChromeClient = originalWebChromeClient;  

  3.   

  4.     for(final WebView webView : webViews){  

  5.   

  6.         if(webView != null){   

  7.             inst.runOnMainSync(new Runnable() {  

  8.                 public void run() {  

  9.                     webView.getSettings().setJavaScriptEnabled(true);  

  10.                     webView.setWebChromeClient(robotiumWebClient);  

  11.   

  12.                 }  

  13.             });  

  14.         }  

  15.     }  

  16. }  

第三步:將提示框中的消息存入WebElement Java bean中

        獲取到了prompt提示框中的消息後,接下來就是對這些已通過處理含特殊格式的消息進行解析處理了,依次獲得WebElement的id、text、name等字段。


[java] view plaincopy在CODE上查看代碼片派生到個人代碼片

  1. private WebElement createWebElementAndSetLocation(String information, WebView webView){  

  2.     String[] data = information.split(";,");            //將消息按;,符號分割,其中;,符號是在前面執行JS時加入的  

  3.     String[] elements = null;  

  4.     int x = 0;  

  5.     int y = 0;  

  6.     int width = 0;  

  7.     int height = 0;  

  8.     Hashtable<String, String> attributes = new Hashtable<String, String>();  

  9.     try{  

  10.         x = Math.round(Float.valueOf(data[5]));  

  11.         y = Math.round(Float.valueOf(data[6]));  

  12.         width = Math.round(Float.valueOf(data[7]));  

  13.         height = Math.round(Float.valueOf(data[8]));      

  14.         elements = data[9].split("\\#\\$");  

  15.     }catch(Exception ignored){}  

  16.   

  17.     if(elements != null) {  

  18.         for (int index = 0; index < elements.length; index++){  

  19.             String[] element = elements[index].split("::");  

  20.             if (element.length > 1) {  

  21.                 attributes.put(element[0], element[1]);  

  22.             } else {  

  23.                 attributes.put(element[0], element[0]);  

  24.             }  

  25.         }  

  26.     }  

  27.   

  28.     WebElement webElement = null;  

  29.   

  30.     try{  

  31.         webElement = new WebElement(data[0], data[1], data[2], data[3], data[4], attributes);//將id、text、name等字段存入  

  32.         setLocation(webElement, webView, x, y, width, height);  

  33.     }catch(Exception ignored) {}  

  34.   

  35.     return webElement;  

  36. }  

[java] view plaincopy在CODE上查看代碼片派生到個人代碼片

  1. /** 

  2.  * Sets the location of a {@code WebElement}  

  3.  *  

  4.  * @param webElement the {@code TextView} object to set location  

  5.  * @param webView the {@code WebView} the text is shown in 

  6.  * @param x the x location to set 

  7.  * @param y the y location to set 

  8.  * @param width the width to set 

  9.  * @param height the height to set 

  10.  */  

  11.   

  12. private void setLocation(WebElement webElement, WebView webView, int x, int y, int width, int height ){  

  13.     float scale = webView.getScale();  

  14.     int[] locationOfWebViewXY = new int[2];  

  15.     webView.getLocationOnScreen(locationOfWebViewXY);  

  16.   

  17.     int locationX = (int) (locationOfWebViewXY[0] + (x + (Math.floor(width / 2))) * scale);  

  18.     int locationY = (int) (locationOfWebViewXY[1] + (y + (Math.floor(height / 2))) * scale);  

  19.   

  20.     webElement.setLocationX(locationX);  

  21.     webElement.setLocationY(locationY);  

  22. }  

至此,WebElement對象中包含了id、text、name等字段,還包含了x、y座標,知道了座標後就能夠像其它Android中的原生View同樣根據座標發送點擊事件。

相關文章
相關標籤/搜索