Android-如何使用WebView的valuateJavascript获取纯HTML?JSOUP无法解析结果HTML

Sha*_*sul 6 android android-webview jsoup

我正在使用下面的代码来获取HTML,但我没有获取纯HTML,它包含非转义字符。我正在使用无法解析此HTML的JSOUP解析器。

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

我从上面的代码中获取此html字符串。

"\u003Chtml>\u003Chead>\n    \u003Cmeta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n    \u003Cmeta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    \u003Clink rel=\"shortcut icon\" href=\"https://www.xyx.com/favicon.ico\" type=\"image/x-icon\">\n    \u003Clink rel=\"icon\" href=\"https://www.xyx.com/favicon.ico\" type=\"image/x-icon\">\n    \n    \u003Ctitle>Page Not Found! : BJSBuzz\u003C/title>\n\n    \u003C!-- \n\tOpen Source Social Network (Ossn)/script>\u003C/body>\u003C/html>"
Run Code Online (Sandbox Code Playgroud)

Sha*_*haw 7

您应该使用 JsonReader 来解析值:

webView.evaluateJavascript("(function() {return document.getElementsByTagName('html')[0].outerHTML;})();", new ValueCallback<String>() {
    @Override
    public void onReceiveValue(final String value) {
        JsonReader reader = new JsonReader(new StringReader(value));
        reader.setLenient(true);
        try {
            if(reader.peek() == JsonToken.STRING) {
                String domStr = reader.nextString();
                if(domStr != null) {
                    handleResponseSuccessByBody(domStr);
                }
            }
        } catch (IOException e) {
            // handle exception
        } finally {
            IoUtil.close(reader);
        }
}
Run Code Online (Sandbox Code Playgroud)

});


KnI*_*fER 5

尝试这个

v=StringEscapeUtils.unescapeJavaScript(v.substring(1,v.length()-1));
Run Code Online (Sandbox Code Playgroud)

unescapeJavaScript 来自 apache commons-lang

android webview 这么多的字符串处理,为什么...上一个回答中提供
removeUTFCharacters方法不够干净。仍然存在诸如\".