標籤:回呼函數 ref from 技術分享 列印 爬取 事件 ext img
第一個nodejs爬蟲:爬取豆瓣電影圖片存入本地:
首先在命令列下 npm install request cheerio express -save;
代碼:
var http = require(‘https‘); //使用https模組var fs = require(‘fs‘);//檔案讀寫var cheerio = require(‘cheerio‘);//jquery寫法擷取所得頁面dom元素var request = require(‘request‘);//發送request請求var i = 0;var url = "https://movie.douban.com/subject/1889243/?from=subject-page";//初始url function fetchPage(x) { //封裝一層函數,方便遞迴調用 startRequest(x);}function startRequest(x) { //採用http模組向伺服器發起一次get請求 http.get(x, function(res) { //get到x網址,成功執行回呼函數 var html = ‘‘; //用來儲存請求網頁的整個html內容 res.setEncoding(‘utf-8‘); //防止中文亂碼 //監聽data事件,每次取一塊資料 res.on(‘data‘, function(chunk) { html += chunk; }); //監聽end事件,如果整個網頁內容的html都擷取完畢,就執行回呼函數 res.on(‘end‘, function() { var $ = cheerio.load(html); //採用cheerio模組解析html var news_item = { //擷取電影的標題 title: $(‘.related-info h2 i‘).text().trim(), //i是用來判斷擷取頁數 i: i = i + 1, }; console.log(news_item); //列印新聞資訊 var news_title = $(‘.related-info h2 i‘).text().trim(); savedContent($, news_title); //儲存每篇文章的內容及文章標題 savedImg($, news_title); //儲存每篇文章的圖片及圖片標題 //下一篇電影的url nextLink = $(".recommendations-bd dl:last-child dd a").attr(‘href‘); if(i <= 10) { //爬取10頁 fetchPage(nextLink); } }); }).on(‘error‘, function(err) { //http模組的on data,on end ,on error事件 console.log(err); });}//儲存標題函數function savedContent($, news_title) { $(‘#link-report span‘).each(function(index, item) { var x = $(this).text(); x = x + ‘\n‘; //將新聞常值內容一段一段添加到/data檔案夾下,並用新聞的標題來命名檔案 fs.appendFile(‘./data/‘ + news_title + ‘.txt‘, x, ‘utf-8‘, function(err) { if(err) { console.log(err); } }); })}//該函數的作用:在本機存放區所爬取到的圖片資源function savedImg($, news_title) { $(‘#mainpic img‘).each(function(index, item) { var img_title = $(‘#content h1 span‘).text().trim(); //擷取圖片的標題 if(img_title.length > 35 || img_title == "") { //圖片標題太長 img_title = "Null"; } var img_filename = img_title + ‘.jpg‘; var img_src = $(this).attr(‘src‘); //擷取圖片的url //採用request模組,向伺服器發起一次請求,擷取圖片資源 request.head(img_src, function(err, res, body) { if(err) { console.log(err); } }); request(img_src).pipe(fs.createWriteStream(‘./image/‘ + news_title + ‘---‘ + img_filename)); //通過流的方式,把圖片寫到本地/image目錄下,並用標題和圖片的標題作為圖片的名稱。 })}fetchPage(url); //主程式開始運行
第一個nodejs爬蟲:爬取豆瓣電影圖片