2013-11-21 40 views
0

我正在解析一個網頁,我可以解析id但不是類..這就是我的意思;我解析整個消息的包裝標識:如何在jsoup解析中選擇類

protected String getBlogStats() throws Exception { 
       String result = ""; 
       // get html document structure 
       Document document = Jsoup.connect(BLOG_URL).get(); 
       // selector query 
       Elements nodeBlogStats = document.select("div#news_wrapper"); 
       // check results 
       if(nodeBlogStats.size() > 0) { 
        // get value 
        result = nodeBlogStats.get(0).text(); 
       } 

       // return 
       return result; 
      } 

和它的作品,我可以顯示的一切,但我需要選擇此包裝內只有H3標籤,所以我這樣tryied:

protected String getBlogStats() throws Exception { 
       String result = ""; 
       // get html document structure 
       Document document = Jsoup.connect(BLOG_URL).get(); 
       // selector query 
       Elements nodeBlogStats = document.select("div#news_wrapper .news-col-1 h3"); 
       // check results 
       if(nodeBlogStats.size() > 0) { 
        // get value 
        result = nodeBlogStats.get(0).text(); 
       } 

       // return 
       return result; 
      } 

news-col-1是一個類..但活動是空白..有沒有另一種方法來編寫類與jsoup解析?由於

+0

你可以像這樣寫getElementsByClassName(「yourclassname」) –

+0

你可以分享你正試圖解析的url嗎? –

+0

http://www.multiplayer.it –

回答

2

一種可能的方式來獲得所有的H3標籤內該div使用類:

Elements nodeBlogStats = doc.select("div.news-col-0 h3"); 

它不會與.news-col-1工作,因爲沒有<h3>標籤是該分區的直接孩子。當你評論,該ID還將努力:

Elements nodeBlogStats = doc.select("div#news_wrapper h3"); 

你的代碼只返回第一H3,而不是全部的原因是因爲你設置的結果是隻有在nodeBlogStats的第一個元素的文本(當你說get(0)):

if(nodeBlogStats.size() > 0) { 
    // get value 
    result = nodeBlogStats.get(0).text(); 
} 

考慮返回ListnodeBlogStats.text()如果你希望所有的H3文字。


更新:

所以,你可以改變你的方法返回一個ArrayList

protected ArrayList<String> getBlogStats() throws Exception { 
    // get html document structure 
    Document document = Jsoup.connect(BLOG_URL).get(); 
    // selector query 
    Elements nodeBlogStats = document.select("div#news_wrapper"); 
    // check results 
    ArrayList<String> list = new ArrayList<String>(); 
    for (Element e : nodeBlogStats) { 
     list.add(e.text()); 
    } 
    return list; 
} 
+0

現在我嘗試..你認爲很難創建一個從此代碼開始的列表?你能幫我嗎?這正是我需要:) –

+0

@David_D看到我更新的答案,希望有所幫助。 – ashatte

+0

mmh這個錯誤是什麼? ''<>'操作符不允許在1.7以下的源代碼級別沒有看到......它在'new ArrayList <>();' –