node 寫的簡單爬蟲
阿新 • • 發佈:2018-02-10
color cheerio spa blog post 新浪 爬取 ext tex
安裝cheerio
npm install cheerio --save
引入http和cheeri
var http=require("http"); var cheerio=require("cheerio");
1.爬取新聞
我們選擇新浪新聞來進行爬取
http://news.sina.com.cn/china/
http.get(url,function(res){ var html=‘‘; res.on(‘data‘,function(data){ html +=data }) res.on(‘end‘, function() { var $=cheerio.load(html); $("#subShowContent2_static .news-item h2").each((iten,i)=>{ console.log($(i).text()); }) console.log("數據加載完畢"); }); }).on(‘error‘, function() { console.log("獲取數據出錯!") });
結果如下:
2.爬取圖片
我們選擇天極網的圖片進行爬取
http://pic.yesky.com/
http.get(url, function (res) { var imageData =‘‘; res.on(‘data‘,function(data){ //圖片加載到內存變量 imageData += data; }).on(‘end‘,function(){ //圖片加載完 var $=cheerio.load(imageData); $Imgs = $(‘img‘), $Imgs.each((iten,i)=>{ console.log($(i).attr(‘src‘)+"------"); }) }); });
結果如下:
node 寫的簡單爬蟲