DIV CSS 佈局教程網

用 JavaScript 與 Ajax 做批次抓取:分段請求與結果寫檔
編輯:AJAX基礎知識     

這支腳本示範一種「分段抓取」的寫法:設定起始編號、結束編號與每次抓取的筆數,程式就自動一段一段地請求,把結果存成本地檔案,直到抓完為止。適合需要批次取得多頁資料的情境。

前端:參數設定與遞迴請求

<html>
<head>
<script language="javascript"><!--
function getit(){
  if(document.getElementById("url").value == ""){ alert("請輸入網址"); return false; }
  if(document.getElementById("count").value == ""){ alert("請輸入每次筆數"); return false; }
  if(document.getElementById("num").value == ""){ alert("請輸入起始編號"); return false; }
  if(document.getElementById("end").value == ""){ alert("請輸入結束編號"); return false; }

  var url   = document.getElementById("url").value;
  var count = document.getElementById("count").value;
  var num   = document.getElementById("num").value;
  var end   = document.getElementById("end").value;
  sendCall(url, count, num, end);
}

function sendCall(url, count, num, end){
  if(parseInt(num) >= parseInt(end)){ return false; }   // 抓完了
  var nurl = url + "?count=" + count + "&num=" + num;

  var xmlHttp;
  if(window.ActiveXObject){
    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  }else if(window.XMLHttpRequest){
    xmlHttp = new XMLHttpRequest();
  }

  xmlHttp.onreadystatechange = function(){
    if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
      var str = xmlHttp.responseText;
      var msg = document.getElementById("getmsg");
      if(str.match(/thereisnothing/)){
        msg.innerHTML = "資料已經完成傳輸!";
      }else{
        write(str, count, num);
        var next = parseInt(num) + parseInt(count);
        sendCall(url, count, next, end);                // 遞迴下一段
      }
    }
  }

  xmlHttp.open('POST', nurl, true);
  xmlHttp.send(null);
}

function write(str, count, num){
  var fso = new ActiveXObject("Scripting.FileSystemObject");
  var end = parseInt(num) + parseInt(count);
  var name = "e:\\" + num + "-" + end + ".txt";
  var a = fso.CreateTextFile(name, true);
  a.WriteLine(str);
  a.Close();
  document.getElementById("num").value = end;
  document.getElementById("getmsg").innerHTML =
    "我已經在你的 E 槽根目錄下產生了一個 " + name + " 的檔案!";
}
// -->
</script>
</head>
<body>

<div>設定參數後開始取得資料:</div>

<input id="url" value="https://www.example.com/test.asp" size="50">
<input type="button" value="開始" onclick="javascript:getit();"><br><br>
<div id="getmsg"></div>
<br><br>

每次筆數:<input name="count" id="count" type="text" value="1000" size="30" /><br><br>
起始編號:<input name="num" id="num" type="text" value="0" size="30" /><br><br>
結束編號:<input name="end" id="end" type="text" value="100" size="30" /><br><br>

</body></html>

它是怎麼跑的

sendCall() 是核心。每次呼叫時先檢查 num 是否已達 end,沒到就發出請求;回應回來後,若內容不是結束標記 thereisnothing,就寫檔,然後把 num 往前推 count,再遞迴呼叫自己。

因為是非同步請求,這個遞迴實際上是「等回應回來才發下一個請求」,所以不會同時送出大量連線把伺服器或網路打爆。這比用迴圈一次送出所有請求要穩妥得多。

寫檔的部分

範例用 Scripting.FileSystemObject 把每段結果存成 e:\num-end.txt,並把 num 更新為下一段的起點,讓終端機狀態能被保留。

這份程式不能這樣用在網路上

有幾個問題必須先講清楚:

  1. FileSystemObject 只有 IE 能用,而且需要降低安全性設定。瀏覽器沙箱的存在正是為了防止網頁任意寫入使用者本機檔案。正式做法應該是把資料回傳到自己的伺服器端,由後端寫檔或寫入資料庫。
  2. 用來大量抓取第三方網站的資料,多數網站的服務條款是禁止的。原範例甚至提到可以拿來「刷票」,那類用途請勿嘗試。抓取前務必確認對方的 robots.txt 與使用條款,並 respect 對方的 Retry-After 與 rate limit。
  3. 缺少錯誤重試。原作者的結語也提到,改進方向是防止網路擁塞導致的中斷。實務上應該加入:請求逾時、失敗後指數退避重試、中斷後能從上次的 num 續跑(把進度寫進 localStorage 或回報給後端)。
  4. 同網域的跨來源限制。瀏覽器有同源政策,前端無法直接抓取任意網域的內容。範例中那段 netscape.security.PrivilegeManager 是舊 Firefox 的寫法,現代瀏覽器已完全移除。合法做法是由自己的伺服器端代理請求。

值得學的設計思路

撇開這些問題,這份程式有兩個想法值得留下來:分段遞迴(不一次送出所有請求,等前一個完成才發下一個)以及狀態可續作(把當前進度記下來,中斷後能接著跑)。這兩個模式在任何需要批次處理大量請求的場景中都用得上,只是要換成合法且安全的方式實作——由後端排隊、前端只負責顯示進度。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved