Jsoup解析HTML,包括span标签

时间:2012-01-20 21:27:16

标签: java parsing jsoup

我有一个格式如下的HTML

<article class="cik" id="100">
<a class="ci" href="/abc/1001/STUFF">
              <img alt="Micky Mouse" src="/images/1001.jpg" />
              <span class="mick vtEnabled"></span>

</a>

<div>
         <a href="/abc/1001/STUFF">Micky Mouse</a>
         <span class="FP">$88.00</span>&nbsp;&nbsp;<span class="SP">$49.90</span>

</div>
</article>

在上面的代码中,文章中的标签有一个span class =“mick vtEnabled”,没有标签。我想检查带有指定类名的span标记是否存在于article标记中。我怎么做?我尝试选择(“&gt; a [href]&gt; span.mick vtEnabled”)并检查尺寸。对于所有文章标签,它都保持为0,无论其是否设置。任何输入?

1 个答案:

答案 0 :(得分:1)

从单个article代码开始会很好:

final String test = "<article class=\"cik\" id=\"100\"><a class=\"ci\" href=\"/abc/1001/STUFF\"><img alt=\"Micky Mouse\" src=\"/images/1001.jpg\" /></a><div><a href=\"/abc/1001/STUFF\">Micky Mouse</a><span class=\"FP\">$88.00</span>&nbsp;&nbsp;<span class=\"SP\">$49.90</span></div></article>";
final Elements articles = Jsoup.parse(test).select("article");
for (final Element article : articles) {
    final Elements articleImages = article.select("> a[href] > img[src]");
    for (final Element image : articleImages) {
        System.out.println(image.attr("src"));
    }
    final Elements articleLinks = article.select("> div > a[href]");
    for (final Element link : articleLinks) {
        System.out.println(link.attr("href"));
        System.out.println(link.text());
    }
    final Elements articleFPSpans = article.select("> div > span.FP");
    for (final Element span : articleFPSpans) {
        System.out.println(span.text());
    }
}
    final Elements articleSPSpans = article.select("> div > span.SP");
    for (final Element span : articleSPSpans) {
        System.out.println(span.text());
    }
}

打印:

/images/1001.jpg
/abc/1001/STUFF
Micky Mouse
$88.00
$49.90