arena
arena

Reputation: 378

Cound divs inside div with Jsoup

I have a page where several status can be found. I would like to count all serviceStatus-OK and serviceStatus-DOWN divs on the page. Unfortunately I cannot modify the page, I need to verify all service is up and running. My idea is that, load the page, count all OK status. If 5 service has 5 OK, we are good. If there is any DOWN, we are not ok.

Any ideas?

Source code:

    <span id="content">
                    <div class="status">
                        <div class="serviceName">
                            Some name <br />
                            http://blablaservice1
                        </div>
                        <div class="serviceStatus-OK">
                            OK
                        </div>
                    </div>

                    <div class="status">
                        <div class="serviceName">
                            Some other name <br />
                            http://blablaservice2
                        </div>
                        <div class="serviceStatus-DOWN">
                            DOWN
                        </div>
                    </div>

My code:
Elements services = doc.select("span#conent");
        Element content = doc.getElementById("content");
        Elements servicesOks = content.getElementsByTag("status");

        int upCounter = 0;
        int downCounter = 0;
        for (Element y : servicesOks) {
            if (y.hasClass("status-OK")) {
                upCounter++;
            }
        }

        for (Element y : servicesOks) {
            if (y.hasAttr("status-DOWN")) {
                downCounter++;
            }
        }


        System.out.println("OK Systems: " + upCounter);
        System.out.println("DOWN Systems: " + upCounter);

My output is:

OK Systems: 0
DOWN Systems: 0

Upvotes: 0

Views: 146

Answers (1)

TDG
TDG

Reputation: 6151

You can find the number of okays and downs like this:

Document doc = Jsoup.parse(input);
Elements OK = doc.select(".serviceStatus-OK");
Elements down = doc.select(".serviceStatus-DOWN");
System.out.println("OK - " + OK.size());
System.out.println("DOWN - " + down.size());

Find all the elements with the names serviceStatus-OK and serviceStatus-DOWN, and then count the number of items of each kind (elemnts is just a list).

Upvotes: 1

Related Questions