Nodejs爬蟲實戰(三)

1. 抽取函數處理

  1. 引入模塊

  2. http協議和https協議兩種,既有不同,那麼模塊引入創建的變量自然不同

  3. url對象的parse方法能獲得http或者https協議的信息。以http://example.com:8080/one?a爲例打印。

     {
         protocol : 'http:' ,
         auth : null ,
         host : 'example.com:8080' ,
         port : '8080' ,
         hostname : 'example.com' ,
         hash : null ,
         search : '?a=index&t=article&m=default',
         query : 'a=index&t=article&m=default',
         pathname : '/one',
         path : '/one?a=index&t=article&m=default',
         href : 'http://example.com:8080/one?a=index&t=article&m=default'
     }
    
  4. protocol屬性保存了協議

     if(urlObj.protocol == 'http:'){
     	http = require('http');
     }
     else{
     	http = require('https');
     }
    
  5. 處理error頁面

     req.on('error',()=>{
     	console.log('404');
     })
    

    ####### 完整代碼

     const fs = require('fs');
     const url = require('url')
     GetUrl('https://detail.tmall.com/item.htm?spm=a230r.1.14.6.68624507tWuF7E&id=560257961625&cm_id=140105335569ed55e27b&abbucket=18&sku_properties=10004:709990523',data=>{
         fs.writeFile('iponex.html',data);
     })
     function GetUrl(sUrl,success){
     	var urlObj = url.parse(sUrl);
     	var http ='';
     	if(urlObj.protocol == 'http:'){
     		http = require('http');
     	}
     	else{
     		http = require('https');
     	}
     
     	let req = http.request({
     		'hostname':urlObj.hostname,
     		'path':urlObj.path
     	},res=>{
     		console.log(res)
     		
     		var arr = [];
     		res.on('data',buffer=>{
     			arr.push(buffer);
     		});
     		res.on('end',()=>{
     			let b = Buffer.concat(arr);
     			success && success(b);
     		})
     		
     	});
     
     	req.end();
     	req.on('error',()=>{
     		console.log('404');
     	})
     }
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章