Android 使用Jsoup解析Html


想要做一個看新聞的應用,類似Cnbeta客戶端的東西。大致思路如下:根據鏈接獲取新聞列表頁的html代碼,然后解析,找到所有的新聞標題和新聞鏈接用listView顯示,當點擊ListView的Item再加載相應的新聞內容。

其中獲取html代碼,可以使用如下代碼實現:

public String getHtmlString(String urlString) {  
    try {  
        URL url = new URL(urlString);  
        URLConnection ucon = url.openConnection();  
        InputStream instr = ucon.getInputStream();  
        BufferedInputStream bis = new BufferedInputStream(instr);  
        ByteArrayBuffer baf = new ByteArrayBuffer(500);  
        int current = 0;  
        while ((current = bis.read()) != -1) {  
            baf.append((byte) current);  
        }  
        return EncodingUtils.getString(baf.toByteArray(), "gbk");  
    } catch (Exception e) {  
        return "";  
    }  
}  

傳入一個網頁鏈接,將返回此鏈接的html代碼(String)。

然后就是解析此html代碼了。經過google,發現了java的一個很好用的解析html的庫,Jsoup:http://jsoup.org/

很容易使用,方法類似javascript和JQuery。只需先構建一個Jsoup的Document對象,然后就可以像使用js一個解析html了

String htmlString = getHtmlString("http://www.cnbeta.com");  
Document document = Jsoup.parse(htmlString);  

比如要獲取cnbeta的html的title,只需:

String title = document.head().getElementsByTag("title").text();  

另外構建Document的時候也可以直接使用URL,像這樣:

Document doc = Jsoup.parse(new URL("http://www.cnbeta.com"), 5000);  

其中5000是連接網絡的超時時間。

 

 

有關Jsoup的下載和更多介紹,見其官網:http://jsoup.org/

我寫的一個demo,點擊按鈕后會加載然后顯示cnbeta首頁的所有新聞標題和鏈接地址,下載:http://download.csdn.net/detail/barryhappy/4151450 ,zip包里有jsoup的jar包,導入項目后可能需要手動導入此jar包。

運行效果圖——

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM