使用jsoup提取和分组元素

时间:2013-06-26 09:07:56

标签: java jsoup

我想得到这个输出:

  

** * * 电影片名: ** * **
第二次世界大战   的
** * ** 施放: * * * ***
Brad Pitt
Mireille Enos
James Badge Dale

     

** * * 电影片名: ** * **
怪兽大学
** * ** 施放: ** * 的***
约翰尼   Depp
Watsons Junior

<h2 itemprop="name">World War Z</h2>
<div class=info>‎1hr 56min‎‎ - Rated PG13‎‎ - Action/Drama/Horror‎‎ - English‎<br>
 - Cast: 
<span itemprop="actors">Brad Pitt</span>, 
<span itemprop="actors">Mireille Enos</span>, 
<span itemprop="actors">James Badge Dale</span>
</div>

<h2 itemprop="name">Monsters University</h2>
<div class=info>‎2hr 30min‎‎ - Rated PG13‎‎ - Comedy‎‎ - English‎<br>
 - Cast: 
<span itemprop="actors">Johnny Depp</span>, 
<span itemprop="actors">Watsons Junior</span>
</div>

我试过这样做:

    Elements movieTitle = doc.select("h2");
    for (Element src : movieTitle) {
        for (int i = 0; i < movieTitle.size(); ++i) {
            title += movieTitle.get(i).text() + "\n";
        }
        break;
    }

    Elements casts = doc.select("span[itemprop=actors]");
    for (Element sr : casts) {
        for (int i = 0; i < casts.size(); ++i) {
            cast += casts.get(i).text() + "\n";
        }
        break;
    }
System.out.println("*************Movie Titles:************* \n" + title);
System.out.println("*************Casts:************* \n" + cast);

但输出是:

  

** * * 电影片名: ** * **
   第二次世界大战   怪兽大学

  的
** * ** 施放: * * * ***
布拉德·皮特·米雷耶·伊诺斯·詹姆斯·巴吉戴尔·约翰尼·德普为屈臣氏少年

如何根据电影对演员表进行分组?

1 个答案:

答案 0 :(得分:0)

这将为您提供所需格式的结果。

 Elements items = doc.select("h2");
    for (Element movieElement : items) {

        //Here you get movie name from movieElement
        Elements castElemets =  movieElement.nextElementSibling().select("span[itemprop=actors]");
        //loop through the castElemnts for corresponding Movie
    }