Java – Get data from the div class via JSOUP

Get data from the div class via JSOUP… here is a solution to the problem.

Get data from the div class via JSOUP

I need to get the value “8.32” from “rnicper”, the value “36 mg” from “rnstr”, and the value “20/80 PG/VG” from “nirat”.

<div class="recline highlight" id="rnic">
          <div class="rlab"><span class="nopr indic indic-danger"></span>Nicotine juice <span id="rnstr">36 mg</span> (<span id="nirat">20/80 PG/VG</ span>)</div>
          <div class="runit" id="rnicml">2.08</div>
          <div class="rdrops" id="rnicdr">73</div>
          <div class="rgrams" id="rnicg" style="display: none; ">2.53</div>
          <div class="rpercent" id="rnicper">8.32</div><br>
        </div>

I tried various methods but nothing happened.

doc.getElementById("rnicper").outerHtml();
doc.getElementById("rnicper").text();
doc.select("div#rnicper");
doc.getElementsByAttributeValue("id", "rnicper").text();

Please tell me, how can I get this information using JSOUP?

Chintak Patel updates

AsyncTask asyncTask = new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] objects) {
                Document doc = null;
                try {
                    doc = Jsoup.connect("http://e-liquid-recipes.com/recipe/2254223/RY4D%20Vanilla%20Swirl%20DL").get();
                } catch (IOException e) {
                    e.printStackTrace();
                }

String content =  doc.select("div[id=rnicper]").text();
                Log.d("content", content);

return null;
            }
        };
        asyncTask.execute();

Solution

The parameter values you are trying to get are not part of the initial HTML, but are set by JavaScript after the page loads.
Jsoup only fetches static HTML and does not execute JavaScript code.

To get what you want, you can use tools like HtmlUnit or Selenium.

HtmlUnit example:

    try (final WebClient webClient = new WebClient()) {
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        final HtmlPage page = webClient
                .getPage("http://e-liquid-recipes.com/recipe/2254223/RY4D%20Vanilla%20Swirl%20DL");

System.out.println(page.getElementById("rnicper").asText());

}

Related Problems and Solutions