从ID选择中选择多个类别

时间:2018-07-31 14:06:27

标签: java jsoup

我有以下XML

<div id="Master25" class="open-pane" role="tabpanel">
<a href="/option1" title="option1" class="top-element ">
    <div class="top-element-description">
        <div class="top-element-option-title">Spain</div>
        <div class="top-element-option-description">Test1</div>
    </div>
        <span class="top-element-price">23&euro;</span>
</a>
<a href="/option2" class="top-element ">
    <div class="top-element-description">
        <div class="top-element-option-title">Greece</div>
        <div class="top-element-option-description">Test2</div>
    </div>
        <span class="top-element-price">25&euro;</span>
</a>
<a href="/option3" class="top-element ">
    <div class="top-element-description">
        <div class="top-element-option-title">Germany</div>
        <div class="top-element-option-description">Test3</div>
    </div>
        <span class="top-element-price">26&euro;</span>
</a>
<a href="/option4" class="top-element ">
    <div class="top-element-description">
        <div class="top-element-option-title">Austria</div>
        <div class="top-element-option-description">Test4</div>
    </div>
        <span class="top-element-price">29&euro;</span>
</a>

如何制作选择器,以便获得:

  1. 西班牙,Test1
  2. 希腊,Test2
  3. 德国,Test3
  4. 奥地利,Test4

2 个答案:

答案 0 :(得分:2)

子选择器怎么样?

a > div

如果我在Jsoup online中测试

通过您的输入,我得到:

Spain Test1
Greece Test2
Germany Test3
Austria Test4

答案 1 :(得分:1)

您可以按以下方式使用jsop:

    String html = new String(Files.readAllBytes(Paths.get("test.txt")));

    Document doc = Jsoup.parse(html);
    Elements elements = doc.body().getElementsByClass("top-element-description");

    for (Element el : elements) {
        System.out.println(el.text());
    }

输出为:

Spain Test1
Greece Test2
Germany Test3
Austria Test4