我正在解析一个包含许多条目的文档(使用JSoup)
<span class="chart_position position-up position-greatest-gains">1</span>
<h1>Beauty And A Beat</h1>
<p class="chart_info">
<a href="/artist/305459/justin-bieber">Justin Bieber Featuring Nicki Minaj</a> <br>
Beauty and a Beat </p>
我可以提取两首单独的歌曲名称和艺术家名单,如下所示:
Elements song = doc.select("div.chart_listing h1");
System.out.println("song: " + song);
Elements li = doc.select("p.chart_info a");
System.out.println("artists: " + li.text());
但是,现在输出如下:
<h1>The Lucky Ones</h1>
<h1>Scream & Shout</h1>
<h1>Clarity</h1>
<h1>We Are Young</h1>
<h1>Va Va Voom</h1>
<h1>Catch My Breath</h1>
<h1>I Found You</h1>
<h1>Sorry</h1>
<h1>Leaving</h1>
artists: Justin Bieber Featuring Nicki Minaj Kerli will.i.am & Britney Spears Nicki Minaj Kelly Clarkson The Wanted Ciara Pet Shop Boys
我希望它看起来像:
1 - Song - Artist
2 - Song - Artist
etc
我一直在查看相关帖子并尝试过这个,但我还没弄明白:
Elements parents = doc.select("div.chart_listing h1");
for (Element parent : parents)
{
Elements categories = parent.select("p.chart_info a");
System.out.print("song: " + parent + " - ");
System.out.print("artist: " + categories.text() + "\n");
}
目前输出一首空白歌曲,如下所示:
song: <h1>Beauty And A Beat</h1> - artist:
song: <h1>The Lucky Ones</h1> - artist:
song: <h1>Scream & Shout</h1> - artist:
仍有两个主要问题:
非常感谢!
--- EDIT
通过使用更大的父级来解决第一个问题:
Elements parents = doc.select("article.song_review");
for (Element parent : parents)
{
Elements titles = parent.select("h1");
Elements categories = parent.select("p.chart_info a");
System.out.print("song: " + titles + " - ");
System.out.print("artist: " + categories.text() + "\n");
}
现在输出如下:
song: <h1>Beauty And A Beat</h1> - artist: Justin Bieber Featuring Nicki Minaj
song: <h1>The Lucky Ones</h1> - artist: Kerli
song: <h1>Scream & Shout</h1> - artist: will.i.am & Britney Spears
关于如何清理%amp的任何想法;并添加编号?
答案 0 :(得分:1)
解决这个问题:
Elements parents = doc.select("article.song_review");
for (Element parent : parents)
{
Elements position = parent.select("span.chart_position");
Elements titles = parent.select("h1");
Elements categories = parent.select("p.chart_info a");
System.out.print("position: " + position.text() + " - song: " + titles.text() + " - ");
System.out.print("artist: " + categories.text() + "\n");
}