[英]JSoup format ouput of children
我正在解析帶有許多這樣的條目的文檔(使用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的任何想法; 並添加編號?
像這樣解決它:
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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.