Reputation: 303
i've a problem with selecting a specific child by order , for exemple looking at this html code :
<html>
<body>
<div class="partA">
1
</div>
<div class="partB">
2
</div>
<div class="partC">
3
</div>
<div class="partB">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div class = "sublassB"> 5 </div>
</div>
<div class="partD">
5
</div>
</body>
</html>
i want using jsoup , get the fourth div for example (body/div[4]/div[5]) , and then get the class name of the fourth div .
i used :eq(n) but it didnt give me the disered result . is there any other way ? thanks in advance :) .
Upvotes: 2
Views: 951
Reputation: 43013
Here is how to write the path body/div[4]/div[5]
as a CSS selector:
body > div:nth-child(4) > div:nth-child(5)
If you use a long path not containing only div or sometimes other tag, simply generate a string on the fly and pass it to Jsoup.
Upvotes: 1
Reputation: 3154
Getting elements with classname is always preferred but still if you want to go by index numbering you can use below code , you must know exact index you want to fetch though
Document doc = Jsoup.connect("http://www.codeinventory.com").get();
Elements body= doc.select("body").get(0);
Elements div = body.select("div").get(3).select("div").get(4); // here just append select("div").get(n) fi you know exact nesting and div number you want
System.out.println(div.attr("class")) // this will give you classname
Upvotes: 1