2012-01-11 75 views
3

一个网页链接数我已经定义了一些网页流量,我打开它的一些网页的在web视图

WebView wv = (WebView) findViewById(R.id.webView1); 
wv.getSettings().setJavaScriptEnabled(true); 
wv.loadUrl("http://mypage.com/"); 

我的问题是我怎么能算在该网页的链接数量?

我的第一个想法是解析html代码并计算该html中的“href”字符串,但这个解决方案听起来像是一个noob解决方案。有更聪明的方法来做到这一点?

回答

1

如果您可以编辑HTML,我认为您可以使用简单的JavaScript函数将计数数据发送回Android。你可以看到有关here

在Javascript功能的答案来计算链路可以是如此简单:

<script type="text/javascript"> 
    function countLinks() 
    { 
     var all_a = document.getElementsByTagName("a"); 
     return all_a.length; 
    } 
</script> 
0

首先声明一个JavaScriptInterface在android系统代码:

public class JavaScriptInterface { 
    Context mContext; 
    /** Instantiate the interface and set the context */ 
    JavaScriptInterface(Context c) { 
     mContext = c; 
    } 
    /** Get number of links */ 
    public void getNumOfLinks(int numOfLinks) { 
     // Use the count as you like 
    } 
} 

然后加入这个界面给你的webview,当你打电话时:

WebView webView = (WebView) findViewById(R.id.webview); 
webView.addJavascriptInterface(new JavaScriptInterface(this), "Android"); 

最后在HTML代码中获取DOM链接的数量并通过接口将其传递给java代码:

<script type="text/javascript"> 
    Android.getNumOfLinks(document.getElementsByTagName("a").length) 
</script>