开发者

Jsoup :eq(n) selector

I hava a test.htm page:

<html>
<body>
    <div class="partA">
    1
    </div>
    <div class="partB">
    2
    </div>
    <div class="partC">
    3
    </div>
    <d开发者_运维知识库iv class="partB">
    4
    </div>
    <div class="partD">
    5
    </div>
</body>
</html>

I want get the first div with class="partB".

Document doc=Jsoup.parse( new File("test.htm"), "utf-8" );
Elements select=doc.select( "div.partB:eq(0)" );
System.out.println( select.get( 0 ).html() );

The run exception is:

 Exception happens:
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.RangeCheck(ArrayList.java:546)
    at java.util.ArrayList.get(ArrayList.java:321)
    at org.jsoup.select.Elements.get(Elements.java:501)
    at Test.main(Test.java:13)

Instead, I got a size=0 elements. Any helps. Thanks~


The eq(n) selector checks the element's sibling index, i.e. the count from the element's parent. So in your example, your selector is looking for a div with both class 'partB' and that is the first child element of its parent (the body). No such element exists, which is why you get a zero length return.

I suggest you use:

Element div = doc.select("div.partB").first();

Which finds the divs by class and then winnows using the list accessor of Element.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜