Android - How to get plain HTML using javascript from Webview? JSOUP could not parse HTML result

I use the code below to get HTML, but I do not get simple HTML, it does not contain escape characters. I am using a JSOUP parser which cannot parse this HTML code.

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

I get this html line from the code above.

"\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>"
+3
source share
2 answers

To remove UTFCharacthers use this function:

 public static StringBuffer removeUTFCharacters(String data) {
        Pattern p = Pattern.compile("\\\\u(\\p{XDigit}{4})");
        Matcher m = p.matcher(data);
        StringBuffer buf = new StringBuffer(data.length());
        while (m.find()) {
            String ch = String.valueOf((char) Integer.parseInt(m.group(1), 16));
            m.appendReplacement(buf, Matcher.quoteReplacement(ch));
        }
        m.appendTail(buf);
        return buf;
    }

and name it inside onReceiveValue (String html) as follows:

@Override
public void onReceiveValue(String html) {
String result = removeUTFCharacters(html).toString();
}

You will get a line with pure html.

Bye alex

+3
source

You should use JsonReader to parse the value:

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

});

0
source

Source: https://habr.com/ru/post/1681774/


All Articles