Android web获取网页html解析数据

2021-04-09  本文已影响0人  wenju
...
web = view.findViewById(R.id.web);
WebSettings webSettings = web.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
// 支持https 与 http 混合加载
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
 webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }

        web.addJavascriptInterface(new InJavaScriptLocalObj(), "java_obj");
        web.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // 获取页面内容
                view.loadUrl("javascript:window.java_obj.showSource("
                        + "document.getElementsByTagName('html')[0].innerHTML);");

                // 获取解析<meta name="share-description" content="获取到的值">
                view.loadUrl("javascript:window.java_obj.showDescription("
                        + "document.querySelector('meta[name=\"share-description\"]').getAttribute('content')"
                        + ");");
            }
        });

 public final class InJavaScriptLocalObj {
     @JavascriptInterface
     public void showSource(String html) {
      //html解析内容
        Log.d("1html------>", html);
     }
    @JavascriptInterface
     public void showDescription(String str) {
        Log.d("2html------>", str);
     }
}
...
上一篇下一篇

猜你喜欢

热点阅读