Android 使用Jsoup解析Html
想要做一個(gè)看新聞的應(yīng)用,類似Cnbeta客戶端的東西。大致思路如下:根據(jù)鏈接獲取新聞列表頁的html代碼,然后解析,找到所有的新聞標(biāo)題和新聞鏈接用listView顯示,當(dāng)點(diǎn)擊ListView的Item再加載相應(yīng)的新聞內(nèi)容。
其中獲取html代碼,可以使用如下代碼實(shí)現(xiàn):
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 ""; } }傳入一個(gè)網(wǎng)頁鏈接,將返回此鏈接的html代碼(String)。
然后就是解析此html代碼了。經(jīng)過google,發(fā)現(xiàn)了java的一個(gè)很好用的解析html的庫,Jsoup:http://jsoup.org/
很容易使用,方法類似javascript和JQuery。只需先構(gòu)建一個(gè)Jsoup的Document對象,然后就可以像使用js一個(gè)解析html了
String htmlString = getHtmlString("http://www.cnbeta.com"); Document document = Jsoup.parse(htmlString);比如要獲取cnbeta的html的title,只需:
String title = document.head().getElementsByTag("title").text();另外構(gòu)建Document的時(shí)候也可以直接使用URL,像這樣:
Document doc = Jsoup.parse(new URL("http://www.cnbeta.com"), 5000);其中5000是連接網(wǎng)絡(luò)的超時(shí)時(shí)間。
?
?
有關(guān)Jsoup的下載和更多介紹,見其官網(wǎng):http://jsoup.org/
我寫的一個(gè)demo,點(diǎn)擊按鈕后會(huì)加載然后顯示cnbeta首頁的所有新聞標(biāo)題和鏈接地址,下載:http://download.csdn.net/detail/barryhappy/4151450?,zip包里有jsoup的jar包,導(dǎo)入項(xiàng)目后可能需要手動(dòng)導(dǎo)入此jar包。
運(yùn)行效果圖——
?
轉(zhuǎn)載于:https://www.cnblogs.com/zhujiabin/p/5310050.html
總結(jié)
以上是生活随笔為你收集整理的Android 使用Jsoup解析Html的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Linux】【通信】1.ping不通
- 下一篇: MySQL自增长主键探究