简体   繁体   中英

How to parse elements with only one class name included using Jsoup?

For this html:

<div id="list">
    <div class="one two three" date="20130121">
        ...
    </div>
    <div class="one" date="20130122">
        ...
    </div>
    <div class="one two" date="20130123">
        ...
    </div>
    <div class="one" date="20130124">
        ...
    </div>
</div>

I would like to extract the date element with class = "one" only, so that if class is included "one" but having other class is not correct.
My expect answer should be date="20130122" and date="20130124"

I tried to use:

Element outestDiv = doc.getElementById("list");
Elements eachDayBox = outestDiv.select("div.one");

But eachDayBox.size() return 4 but not 2. So how to extract with class only "one"?? Also, how to get element in "date"??

Use [attribute=value] in select

Elements eachDayBox = outestDiv.select("div[class=one]"); //class only equal to one

Reference

This will work.

Elements elements = doc.getElementsByAttributeValue("class", "one");
for(int i=0;i<elements.size();i++){
    Element tmp=elements.get(i);
    System.out.println(tmp.attr("date"));
}

获取日期值

String date = eachDayBox .attr("date");

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