我的Android筆記(八)—— 使用Jsoup解析Html
阿新 • • 發佈:2019-02-15
想要做一個看新聞的應用,類似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是連線網路的超時時間。
我寫的一個demo,點選按鈕後會載入然後顯示cnbeta首頁的所有新聞標題和連結地址,下載:http://download.csdn.net/detail/barryhappy/4151450 ,zip包裡有jsoup的jar包,匯入專案後可能需要手動匯入此jar包。
執行效果圖——