【Android 我的部落格APP】1.抓取部落格首頁文章列表內容——網頁資料抓取,androidapp
打算做個自己在部落格園的部落格APP,首先要能訪問首頁擷取資料擷取首頁的文章列表,第一步抓取部落格首頁文章列表內容的功能已實現,在小米2S上的如下:
思路是:通過編寫的工具類訪問網頁,擷取頁面原始碼,通過Regex得到匹配的資料進行處理顯示到ListView上
簡單說明下要點:
1. 使用Apache HttpClient庫實現GET請求。
2. 非同步請求處理。
3. Regex抓取自己需要的資料。
使用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 類代碼。
Regex抓取自己需要的資料
訪問我的部落客頁查看網頁原始碼,很容易找到要抓取文章列表內容的格式都如下:
<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>
因此,得到Regex如下:
"class=\"postTitle2\" href=\"(.*?)\">(.*?)</a>.*?摘要:(.*?)<a.*?posted @(.*?)Y灬葉超 閱讀(.*?) 評論(.*?)<a";
然後通過Regex得到匹配的資料,擷取需要的資料
/** * 連網獲得資料 * * @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; }
其他的不再贅述,具體可查看原始碼:getcsdnlistview.zip
本文地址:http://www.cnblogs.com/yc-755909659/p/4195436.html
PS:本文由Y灬葉超原創,如有轉載請註明出處,謝謝!