繁体   English   中英

如何使用jsoup计算div的数量?

[英]How do I Count the of number of divs using jsoup?

如何使用jsoup计算div的数量?

我需要做的是计算所有“ news_main” div ...

         <h1>Notice to Mariners</h1>
         <form name="filter-form" id="filter-form" action="/notice-to-mariners/"       enctype="multipart/form-data" accept-charset="UTF-8" method="post">
    <div style="display: none"><input type="hidden" name="filter-form" value="1"></div>
    <div style="display:none; width:0px; height:0px;"><p><label class="indent" for="filter-form-leave_blank">If you are human leave this blank:</label><input id="filter-form-leave_blank" class="" type="text" name="filter-form-leave_blank" value=""></p></div><div id="filter"><select class="" name="filter" id="filter-form-filter">
    <option value="form_error">View notices in force</option>
    <option value="1">View notices not in force</option>
    <option value="2">View all notices</option>
    </select><button type="submit">Filter</button></div><!-- / filter --></form>
        <div class="news_main">
        <div class="news_main">
        <div class="news_main">
        <div class="news_main">
        <div class="news_main">

等..等

我尝试了各种方法,但似乎都返回0?

码:

 docNtm = Jsoup.connect("http://www.mhpa.co.uk/notice-to-mariners/").timeout(600000).get();
                           Elements ntmAmount = docNtm.select("div.news_main div"); 

                            System.out.println("size:  " + ntmAmount.size());  

感谢您的任何建议。

编辑:

我现在可以像这样检索所有div:

 10-18 22:41:36.365: I/System.out(14624): size:  0
 10-18 22:41:36.365: I/System.out(14624): size:  0
 10-18 22:41:36.365: I/System.out(14624): size:  0
 10-18 22:41:36.365: I/System.out(14624): size:  0
 10-18 22:41:36.365: I/System.out(14624): size:  0
 10-18 22:41:36.365: I/System.out(14624): size:  0
  .....etc

计数它们的最佳方法是什么?

谢谢

使用Element.getElementsByTag("div"); Element.hasClass("news_main");

Document doc = Jsoup.parse(input, "UTF-8", "http://www.mhpa.co.uk/notice-to-mariners/");

Element content = doc.getElementById("content");
Elements divs = content.getElementsByTag("div");
int ntmAmount = 0;
for (Element div : divs) {
  if (div.hasClass("news_main"))
    ntmAmount++;
}

Element.getElementsByClass("news_main");

...
Elements ntmDivs = content.getElementsByClass("news_main");
int ntmAmount = ntmDivs.size();

更换:

Elements ntmAmount = docNtm.select("div.news_main div"); 

有了这个:

Elements ntmAmount = docNtm.select("div.news_main"); 

我不确定直接方法,但是for循环应该可以...

int count = 0;
for (Element n : ntmAmount) {
    count++;
}

假设ntmAmount是您想要的所有<div>元素的引用...,正如其他人指出的那样,不是。

相反,您需要Elements ntmAmount = docNtm.select("div.news_main")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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