我正在解析一个包含许多这样的条目的文档(使用 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:
两个主要问题仍然悬而未决:
- 如何打印属于歌曲的艺术家?为什么是白的?
- 如何添加编号(这是次要的,但会很好)
非常感谢!
- -编辑
通过使用更大的父级解决了第一个问题:
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; 的任何想法 并添加编号?