如何从webview获取html内容?

111 android webview android-widget

哪个是从webview获取HTML代码的最简单方法?我已经尝试了stackoverflow和google的几种方法,但找不到确切的方法.请提一下确切的方法.

public class htmldecoder extends Activity implements OnClickListener,TextWatcher
{
TextView txturl;
Button btgo;
WebView wvbrowser;
TextView txtcode;
ImageButton btcode;
LinearLayout llayout;
int flagbtcode;
public void onCreate(Bundle savedInstanceState)
{
            super.onCreate(savedInstanceState);
                setContentView(R.layout.htmldecoder);

    txturl=(TextView)findViewById(R.id.txturl);

    btgo=(Button)findViewById(R.id.btgo);
    btgo.setOnClickListener(this);

    wvbrowser=(WebView)findViewById(R.id.wvbrowser);
    wvbrowser.setWebViewClient(new HelloWebViewClient());
    wvbrowser.getSettings().setJavaScriptEnabled(true);
    wvbrowser.getSettings().setPluginsEnabled(true);
    wvbrowser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    wvbrowser.addJavascriptInterface(new MyJavaScriptInterface(),"HTMLOUT");
    //wvbrowser.loadUrl("http://www.google.com");
    wvbrowser.loadUrl("javascript:window.HTMLOUT.showHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");


    txtcode=(TextView)findViewById(R.id.txtcode);
    txtcode.addTextChangedListener(this);

    btcode=(ImageButton)findViewById(R.id.btcode);
    btcode.setOnClickListener(this);

    }

public void onClick(View v)
{
    if(btgo==v)
    {
        String url=txturl.getText().toString();
        if(!txturl.getText().toString().contains("http://"))
        {
            url="http://"+url;
        }
        wvbrowser.loadUrl(url);
        //wvbrowser.loadData("<html><head></head><body><div style='width:100px;height:100px;border:1px red solid;'></div></body></html>","text/html","utf-8");
    }
    else if(btcode==v)
    {
        ViewGroup.LayoutParams params1=wvbrowser.getLayoutParams();
        ViewGroup.LayoutParams params2=txtcode.getLayoutParams();
        if(flagbtcode==1)
        {
            params1.height=200;
            params2.height=220;
            flagbtcode=0;
            //txtcode.setText(wvbrowser.getContentDescription());
        }
        else
        {
            params1.height=420;
            params2.height=0;
            flagbtcode=1;
        }
        wvbrowser.setLayoutParams(params1);
        txtcode.setLayoutParams(params2);

    }
}

public class HelloWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        view.loadUrl(url);
        return true;
    }
    /*@Override
    public void onPageFinished(WebView view, String url)
    {
        // This call inject JavaScript into the page which just finished loading. 
        wvbrowser.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
    }*/

}
class MyJavaScriptInterface
{
    @SuppressWarnings("unused")
    public void showHTML(String html)
    {

        txtcode.setText(html);
    }
}

public void afterTextChanged(Editable s) {
    // TODO Auto-generated method stub

}

public void beforeTextChanged(CharSequence s, int start, int count,
        int after) {
    // TODO Auto-generated method stub

}

public void onTextChanged(CharSequence s, int start, int before, int count) {
    wvbrowser.loadData("<html><div"+txtcode.getText().toString()+"></div></html>","text/html","utf-8");

}

}
Run Code Online (Sandbox Code Playgroud)

Sep*_*phy 103

实际上这个问题有很多答案.以下是其中两个:

  • 这第一个与你的几乎相同,我想我们是从同一个教程中得到的.

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" +
                        "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
            }
        });

        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();
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

这样你通过javascript获取html.这不是最漂亮的方式,但是当你拥有自己的javascript界面​​时,你可以添加其他方法来修补它.


  • 另一种方法是在那里使用HttpClient .

您认为,您选择的选项还取决于您打算如何处理检索到的HTML ...

  • 以上代码对Jellybean及其后续的两个重要更改:1.删除"窗口".来自webview.loadUrl行 - 在定位Jellybean时,javascript界面​​的附加方式不同.2.将@JavascriptInterface放在"public void showHTML"之前 - 这是必要的,因为这样做的安全风险不仅仅是允许调用某些方法. (31认同)
  • webview.addJavascriptInterface仅适用于Jelly Beans和更低版本. (6认同)
  • 这里我开启了远程调试,不管有没有`@JavascriptInterface`都显示`Uncaught ReferenceError: HtmlViewer is not defined` (2认同)

Aka*_*ose 43

在KitKat及以上版本中,您可以evaluateJavascript在webview上使用方法

wvbrowser.evaluateJavascript(
        "(function() { return ('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>'); })();",
         new ValueCallback<String>() {
            @Override
            public void onReceiveValue(String html) {
                Log.d("HTML", html); 
                // code here
            }
    });
Run Code Online (Sandbox Code Playgroud)

有关更多示例,请参阅答案

  • 仅供参考 - 需要API 19. (8认同)
  • 记得把它放到onPageFinished方法中. (3认同)

小智 40

对于android 4.2,别忘了将@JavascriptInterface添加到所有javasscript函数中


yor*_*rkw 10

Android WebView只是另一个渲染引擎,可以呈现从HTTP服务器下载的HTML内容,就像Chrome或FireFox一样.我不知道你需要从WebView获取渲染页面(或屏幕截图)的原因.在大多数情况下,这不是必需的.您始终可以直接从HTTP服务器获取原始HTML内容.

已经发布了关于使用HttpUrlConnection或HttpClient获取原始流的答案.或者,在Android上处理HTML内容解析/处理时有一个非常方便的库:JSoup,它提供了非常简单的API来从HTTP服务器获取HTML内容,并提供HTML文档的抽象表示,以帮助我们管理HTML解析不仅更多的OO风格,但也很容易:

// Single line of statement to get HTML document from HTTP server.
Document doc = Jsoup.connect("http://en.wikipedia.org/").get();
Run Code Online (Sandbox Code Playgroud)

例如,当您想先下载HTML文档然后在将其传递给WebView进行渲染之前添加一些自定义css或javascript时,它非常方便.更多关于他们的官方网站,值得一试.


Tat*_*aki 8

with(webView) {
    settings.javaScriptEnabled = true
    webViewClient = object : WebViewClient() {
        override fun onPageFinished(view: WebView?, url: String?) {
            view?.evaluateJavascript("document.documentElement.outerHTML") {
                val html = it.replace("\\u003C", "<")
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

我发现需要实施的一个接触点在Proguard配置中被"隐藏"了.虽然HTML阅读器在调试应用程序时通过javascript界面​​调用就好了,但是除非在Proguard配置文件中声明了HTML阅读器功能,否则不再在应用程序通过Proguard运行时立即工作,如下所示:

-keepclassmembers class <your.fully.qualified.HTML.reader.classname.here> {
    public *; 
}
Run Code Online (Sandbox Code Playgroud)

在Android 2.3.6,4.1.1和4.2.1上经过测试和确认.