how to get html content from a webview?

后端 未结 12 1766
鱼传尺愫
鱼传尺愫 2020-11-22 04:29

Which is the simplest method to get html code from a webview? I have tried several methods from stackoverflow and google, but can\'t find an exact method. Please mention an

12条回答
  •  无人共我
    2020-11-22 04:59

    Actually this question has many answers. Here are 2 of them :

    • This first is almost the same as yours, I guess we got it from the same tutorial.

    public class TestActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.webview);
            final WebView webview = (WebView) findViewById(R.id.browser);
            webview.getSettings().setJavaScriptEnabled(true);
            webview.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");
    
            webview.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    webview.loadUrl("javascript:window.HtmlViewer.showHTML" +
                            "(''+document.getElementsByTagName('html')[0].innerHTML+'');");
                }
            });
    
            webview.loadUrl("http://android-in-action.com/index.php?post/" +
                    "Common-errors-and-bugs-and-how-to-solve-avoid-them");
        }
    
        class MyJavaScriptInterface {
    
            private Context ctx;
    
            MyJavaScriptInterface(Context ctx) {
                this.ctx = ctx;
            }
    
            public void showHTML(String html) {
                new AlertDialog.Builder(ctx).setTitle("HTML").setMessage(html)
                        .setPositiveButton(android.R.string.ok, null).setCancelable(false).create().show();
            }
    
        }
    }
    

    This way your grab the html through javascript. Not the prettiest way but when you have your javascript interface, you can add other methods to tinker it.


    • An other way is using an HttpClient like there.

    The option you choose also depends, I think, on what you intend to do with the retrieved html...

提交回复
热议问题