简体   繁体   中英

How would I go about using jsoup to parse a specific integer value from this HTML?

I am a first year cs student working on a project for which I need to get the temperature date from a website. I am attempting to do this with Jsoup, but I am finding a lack of good tutorials on getting started. Here is the HTML I am trying to parse from.

    <span class="actual-temp ng-isolate-scope ng-binding" aria-label="Actual Temperature" data-wx-temperature="obs.getTemp()" data-show-temp-unit="true">
        <!-- ngIf: hasValue() -->
        <span data-ng-if="hasValue()" data-ng-bind-template="32" class="ng-scope ng-binding">32</span>
        <!-- end ngIf: hasValue() -->
        <!-- ngIf: hasValue() -->
        <sup data-ng-if="hasValue()" class="deg ng-scope">°</sup>
        <!-- end ngIf: hasValue() -->
        <!-- ngIf: showTempUnit -->
        <sup class="temp-unit ng-scope ng-binding" data-ng-if="showTempUnit" data-ng-bind-template="F">F</sup>

Specifically, I am trying to extract the number 32 from that. Any help would be greatly appreciated!

Based on your little piece of code you provided following would extract the temperature. You probably need to amend the code to work with the full HTML. (for simplicity all checks or optimizations intentionally omitted)

Document doc = Jsoup.parse("<span class=\"actual-temp ng-isolate-scope ng-binding\" aria-label=\"Actual Temperature\" data-wx-temperature=\"obs.getTemp()\" data-show-temp-unit=\"true\">\n"
        + "        <!-- ngIf: hasValue() -->\n"
        + "        <span data-ng-if=\"hasValue()\" data-ng-bind-template=\"32\" class=\"ng-scope ng-binding\">32</span>\n"
        + "        <!-- end ngIf: hasValue() -->\n"
        + "        <!-- ngIf: hasValue() -->\n"
        + "        <sup data-ng-if=\"hasValue()\" class=\"deg ng-scope\">°</sup>\n"
        + "        <!-- end ngIf: hasValue() -->\n"
        + "        <!-- ngIf: showTempUnit -->\n"
        + "        <sup class=\"temp-unit ng-scope ng-binding\" data-ng-if=\"showTempUnit\" data-ng-bind-template=\"F\">F</sup>\n"
        + "   </span>");
Elements rows = doc.getElementsByAttributeValue("class", "ng-scope ng-binding");
String temperature;
for (Element span : rows) {
        temperature = span.text();
}
System.out.println("temperature = " + temperature);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM