2011年10月29日 星期六

應用readUrl函數取得網頁資料

抓取網頁資料在程式設計討論區中可說是常被提及的問題,在之前的「利用WSH環境的JScript抓取網頁資料」文章中,就已經試過抓取網頁資料。現在換到Rhino環境下,也用這個課題來實作一下。
WSH環境下,採用的是Microsoft.XMLHttp物件抓取網頁資料;轉換到Rhino環境下,當然沒有這樣的物件。只是Rhino可以應用Java的物件,所以要達到抓取網頁的功能當然也可以透過呼叫Java的物件來完成。不過殺雞焉用牛刀,Rhino環境即提供函數readUrl()可以抓取網頁資料,已足夠用來抓取一般的網頁資料。
底下程式碼就是使用函數readUrl()抓取樂透彩網站的開獎號碼網頁資料:
/**
 *
 * 使用Rhino的readUrl()函數取得網頁資料。
 *
 * @author ace
 *
 * @version 2011/10/31 v0.1
 *
 * @see <a href="https://developer.mozilla.org/en/Rhino_Shell#readUrl(url_.5B.2C_characterCoding.5D)">readUrl(url [, characterCoding])</a>
 * 
 * @description
 *
 */

load("js/rhino/InitialEnv.js");

try {

  // 威力彩(http://www.taiwanlottery.com.tw/Lotto/SuperLotto638/history.aspx)
  var strSourceURL = new String("http://www.taiwanlottery.com.tw/Lotto/SuperLotto638/history.aspx"); 
  var strTargetFile = new String("C:\\Dev-Rhino\\SuperLotto638.html");

  // 資料寫入檔案(UTF8編碼格式)。
  var filTarget = new java.io.File(strTargetFile);
  var fisTarget = new java.io.FileOutputStream(filTarget); 
  var BufferedWriter = new java.io.BufferedWriter(new java.io.OutputStreamWriter(fisTarget, "UTF-8"));
  
  // 使用Rhino的readUrl()函數讀取網頁內容。
  var URLContent = new String(readUrl(strSourceURL, "UTF-8"));
  
  BufferedWriter.write(URLContent);
}
catch (e) {
  print("執行過程有誤,錯誤訊息:" + e.message);
}
finally {
  if (BufferedWriter != null) {
    BufferedWriter.flush();
    BufferedWriter.close();
  }
}        
抓取網頁資料同樣需要注意編碼格式,以免取得的網頁資料變成亂碼;函數readUrl()的第二個引數即可指定取得網頁的編碼格式,可說是相當方便的設計。

沒有留言:

張貼留言

Related Posts Plugin for WordPress, Blogger...