打算做個自己在博客園的博客APP,首先要能訪問首頁獲取數據獲取首頁的文章列表,第一步抓取博客首頁文章列表內容的功能已實現,在小米2S上的效果圖如下:
思路是:通過編寫的工具類訪問網頁,獲取頁面源代碼,通過正則表達式得到匹配的數據進行處理顯示到ListView上
簡單說明下要點:
1. 使用Apache HttpClient庫實現GET請求。
2. 異步請求處理。
3. 正則表達式抓取自己需要的數據。
使用Apache HttpClient庫實現GET請求。
使用Apache只需簡單三步
HttpClient httpClient = new DefaultHttpClient(); //創建一個HttpClient HttpGet httpGet = new HttpGet(“http://www.cnblogs.com/yc-755909659/”); //創建一個GET請求 HttpResponse response = httpClient.execute(httpGet); //發送GET請求,並響應內容
異步請求處理
異步請求的實現也很簡單,開辟新線程執行請求處理,請求完成通過Handler在主線程處理所獲得的數據。具體看源代碼中MainActivity.java 類代碼。
正則表達式抓取自己需要的數據
訪問我的博客主頁查看網頁源代碼,很容易找到要抓取文章列表內容的格式都如下:
<div class="postTitle"> <a id="homepage1_HomePageDays_DaysList_ctl00_DayList_TitleUrl_0" class="postTitle2" href="http://www.cnblogs.com/yc-755909659/p/4187155.html">【讀書筆記《Android游戲編程之從零開始》】19.游戲開發基礎(游戲音樂與音效)</a> </div> <div class="postCon"><div class="c_b_p_desc">摘要: 在一款游戲中,除了華麗的界面 UI 直接吸引玩家外,另外重要的就是游戲的背景音樂與音效;合適的背景音樂以及精彩的音效搭配會令整個游戲上升一個檔次。在 Android 中。常用於播放游戲背景音樂的類是 MediaPlayer, 而用於游戲音效的則是 SoundPool 類。1. MediaPlayer...<a href="http://www.cnblogs.com/yc-755909659/p/4187155.html" class="c_b_p_desc_readmore">閱讀全文</a></div></div> <div class="clear"></div> <div class="postDesc">posted @ 2014-12-30 12:16 Y灬葉超 閱讀(45) 評論(0) <a href ="http://i.cnblogs.com/EditPosts.aspx?postid=4187155" rel="nofollow">編輯</a></div> <div class="clear"></div>
因此,得到正則表達式如下:
"class=\"postTitle2\" href=\"(.*?)\">(.*?)</a>.*?摘要:(.*?)<a.*?posted @(.*?)Y灬葉超 閱讀(.*?) 評論(.*?)<a";
然后通過正則表達式得到匹配的數據,獲取需要的數據
/** * 聯網獲得數據 * * @return 數據 */ public static List<BlogListInfo> getBlogNetDate(String path, String regex) { List<BlogListInfo> result = new ArrayList<BlogListInfo>(); String blogString = RemoveRN(http_get(path)); Pattern p = Pattern.compile(regex); // 我的博客首頁的源代碼字符串 Matcher m = p.matcher(blogString); while (m.find()) {// 循環查找匹配字串 MatchResult mr = m.toMatchResult(); BlogListInfo info = new BlogListInfo(); info.setBlogUrl(mr.group(1)); info.setBlogTitle(mr.group(2)); info.setBlogSummary(mr.group(3)); info.setBlogTime(mr.group(4)); info.setBlogReadNum(mr.group(5)); info.setBlogReply(mr.group(6)); result.add(info); } return result; }
源代碼地址:https://github.com/YeXiaoChao/getcsdnlistview
本文地址:http://www.cnblogs.com/yc-755909659/p/4195436.html
PS:本文由Y灬葉小超原創,如有轉載請注明出處,謝謝!