Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

android - How I get page source from WebView?

How I get the web page's source from WebView?

I want to only enter www.google.com in my webview and When I entered this site, I want to get the source for example

String a=........;(source) 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I am not sure how far this is going to be helpful. But I have used the below snippet to fetch a small html page's data. I hope it helps you.

Create a class like the one below,

  class MyJavaScriptInterface
  {
      @SuppressWarnings("unused")
      public void processHTML(final String html)
      {
          Log.i("processed html",html);

            Thread OauthFetcher=new Thread(new Runnable() { 

                @Override
                public void run() {

                    String oAuthDetails=null;
                      oAuthDetails=Html.fromHtml(html).toString();
                      Log.i("oAuthDetails",oAuthDetails);

                }
            });OauthFetcher.start();
        }
      } 

Now in your onCreate(),

 webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

     webview.setWebViewClient(new WebViewClient(){

            @Override
            public void onPageFinished(WebView view, final String url) {


                String oAuthUrl=getString("www.google.com");

                if(url.contains(oAuthUrl))
                {
                    Log.i("Contains","Auth URL");

                    twitter_webview.loadUrl("javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
                }
            }
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                progressDialog.show();
            }
      });

And now what happens is that, when your page finishes loading, the JavaScript class will be called, which would retrieve the page source and store it in a String as your requirement.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...