简体   繁体   中英

Jsoup html parsing

<div id="footer">
<div class="row1"></div>
<div class="row2">
    <div class="content">
        <div class="row2col1">
            <div class="moduletable">
                <div class="custom">
                    <p>
                        <span style="color: #ffffff;"></span>
                        <span>
                            26
                        </span>
                    </p>
                    <p></p>

How can I get get value from second span which is 26? I tried

 Elements a = doc.select("div#footer div.row2 div.content div.row2col1 div.moduletable div.custom p");

            for (int i = 1; i < a.size(); i++){
                Element b = a.get(i);
                if (i == 2){
                    if(isNum(b.text().trim())){
                        aw = b.text().trim();
                    }
                    else {
                        aw = "oops";
                    }
                }
            }

but it is not working. Can someone show me how to do this?

Your CSS query selects

<p> <span style="color: #ffffff;"></span> <span> 26 </span> </p>
<p></p>

so as you see these are two <p> elements, first with

<span style="color: #ffffff;"></span> <span> 26 </span>

and second one empty.

If you want to select span elements you should add it to your query like

div#footer div.row2 div.content div.row2col1 div.moduletable div.custom p span

Also if you know that you want to get second element (which index is 1 since elements are indexed from 0 ) you don't need loop, but can simply use a.get(1)

So your code can look more like this

Elements a = doc.select("div#footer div.row2 div.content div.row2col1"
        + " div.moduletable div.custom p span");
//                                      ^^^^^---add this part
String spanValue = a.get(1).text().trim();
if (spanValue.matches("\\d+")) {// I changed this condition a bit just for tests
    aw = spanValue;
} else {
    aw = "oops";
}

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