淺談Node.js爬蟲之網頁請求模組,node.js爬蟲
本文介紹了Node.js爬蟲之網頁請求模組,分享給大家,具體如下:
註:如您下載最新的nodegrass版本,由於部分方法已經更新,本文的例子已經不再適應,詳細請查看開源地址中的例子。
一、為什麼我要寫這樣一個模組?
源於筆者想使用Node.js寫一個爬蟲,雖然Node.js官方API提供的請求遠端資源的方法已經非常簡便,具體參考
http://nodejs.org/api/http.html 其中對於Http的請求提供了,http.get(options, callback)和http.request(options, callback)兩個方法,
看方法便知,get方法用於get方式的請求,而request方法提供更多的參數,例如其它請求方式,請求主機的連接埠等等。對於Https的請求於Http類似。一個最簡單的例子:
var https = require('https');https.get('https://encrypted.google.com/', function(res) { console.log("statusCode: ", res.statusCode); console.log("headers: ", res.headers); res.on('data', function(d) { process.stdout.write(d); });}).on('error', function(e) { console.error(e);});
對於以上代碼,我們無非就是想請求遠程主機,得到響應資訊,例如響應狀態,回應標頭,響應主體內容。其中get方法的第二個參數是一個回呼函數,我們非同步擷取響應資訊,然後,在該回呼函數中,res對象又監聽data,on方法中第二個參數又是一個回調,而你得到d(你請求到的響應資訊)後,很可能在對它進行操作的時候再次引入回調,一層層下去,最後就暈了。。。對於非同步方式的編程,對於一些習慣同步方式寫代碼的同學是非常糾結的,當然國內外已經對此提供了一些非常優秀的同步類庫,例如老趙的Wind.js......好像有點扯遠了。其實,我們調用get最終要得到的無非就是響應資訊,而不關心res.on這樣的監聽過程,因為太懶惰。不想每次都res.on('data',func),於是誕生了今天我要介紹的nodegrass。
二、nodegrass請求資源,像Jquery的$.get(url,func)
一個最簡單的例子:
var nodegrass = require('nodegrass');nodegrass.get("http://www.baidu.com",function(data,status,headers){ console.log(status); console.log(headers); console.log(data);},'gbk').on('error', function(e) { console.log("Got error: " + e.message);});
咋一看,和官方原來的get沒啥區別,確實差不多=。=!只不過少了一層res.on('data',func)的事件監聽回調而已。不管你信不信,反正我看上去感覺舒服多了,第二個參數同樣是一個回呼函數,其中的參數data是響應主體內容,status是響應狀態,headers是回應標頭。得到響應內容,我們就可以對得到的資源提取任何我們感興趣的資訊啦。當然這個例子中,只是簡單的列印的控制台而已。第三個參數是字元編碼,目前Node.js不支援gbk,這裡nodegrass內部引用了iconv-lite進行了處理,所以,如果你請求的網頁編碼是gbk的,例如百度。只需加上這個參數就行了。
那麼對於https的請求呢?如果是官方api,你得引入https模組,但是請求的get方法等和http類似,於是nodegrass順便把他們整合在一塊了。看例子:
var nodegrass = require('nodegrass');nodegrass.get("https://github.com",function(data,status,headers){ console.log(status); console.log(headers); console.log(data);},'utf8').on('error', function(e) { console.log("Got error: " + e.message);});
nodegrass會根據url自動識別是http還是https,當然你的url必須得有,不能唯寫www.baidu.com/而需要http://www.baidu.com/。
對於post的請求,nodegrass提供了post方法,看例子:
var ng=require('nodegrass');ng.post("https://api.weibo.com/oauth2/access_token",function(data,status,headers){ var accessToken = JSON.parse(data); var err = null; if(accessToken.error){ err = accessToken; } callback(err,accessToken); },headers,options,'utf8');
以上是新浪微博Auth2.0請求accessToken的一部分,其中使用nodegrass的post請求access_token的api。
post方法相比get方法多提供了headers要求標頭參數,options--post的資料,它們都是對象字面量的類型:
var headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length':data.length };var options = { client_id : 'id', client_secret : 'cs', grant_type : 'authorization_code', redirect_uri : 'your callback url', code: acode };
三、利用nodegrass做Proxy 伺服器?……**
看例子:
var ng = require('nodegrass'), http=require('http'), url=require('url'); http.createServer(function(req,res){ var pathname = url.parse(req.url).pathname; if(pathname === '/'){ ng.get('http://www.cnblogs.com/',function(data){ res.writeHeader(200,{'Content-Type':'text/html;charset=utf-8'}); res.write(data+"\n"); res.end(); },'utf8'); } }).listen(8088); console.log('server listening 8088...');
就這麼簡單,當然Proxy 伺服器還有複雜的多,這個不算是,但至少你訪問本地8088連接埠,看到的是不是部落格園的頁面呢?
nodegrass的開源地址:https://github.com/scottkiss/nodegrass
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。