nodejs做個爬蟲爬取騰訊動漫內容簡單實現(xiàn)
更新時間:2023年07月24日 09:20:31 作者:紫氣東來_姜波
這篇文章主要為大家介紹了nodejs做個爬蟲爬取騰訊動漫內容簡單實現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
首先上package.json
{ "name": "Spider", "version": "1.0.0", "description": "spider ", "main": "index.js", "dependencies": { "async": "^1.5.0", "cheerio": "^0.19.0", "eventproxy": "^0.3.4", "superagent": "^1.4.0" }, "devDependencies": {}, "scripts": { "test": "node index", "start": "node server.js" } }
server.js
var http = require("http"); var cheerio = require("cheerio"); var fs = require('fs'); //Utility function that downloads a URL and invokes //callback with the data. function downloadPage(url, callback) { http.get(url, function(res) { var data = ""; res.on('data', function(chunk) { data += chunk; }); res.on("end", function() { callback(data); }); }).on("error", function() { callback(null); }); } function start() { var url = 'http://ac.qq.com/Comic/index/type/4/page/'; var url2 = 'http://ac.qq.com/ComicView/index/id/549690/cid/1'; var arr = []; for (var i = 1; i < 13; i++) { downloadPage(url + i, function(data) { if (data) { var $ = cheerio.load(data); $("div.ret-search-result > ul > li.ret-search-item").each(function(i, e) { var json = {}; json.tags = []; json.img = $(e).find('img').attr('data-original'); json.link = $(e).find('a.mod-cover-list-thumb').attr('href'); json.id = json.link.split('/').reverse()[0]; json.title = $(e).find('h3.ret-works-title > a').text(); json.author = $(e).find('p.ret-works-author').text(); json.popular = $(e).find('p.ret-works-tags> span > em').text(); json.description = $(e).find('p.ret-works-decs').text(); $(e).find('p.ret-works-tags>a').each(function(i, e) { json.tags.push($(e).text()); }); downloadImg(json.img); arr.push(json) console.log("done"); // console.log(arr) // fs.writeFileSync('./output.json', JSON.stringify(arr)); // }); }) } }) } } function downloadImg(url) { console.log('string') http.get(url, function(res) { var imgData = ""; res.setEncoding("binary"); //一定要設置response的編碼為binary否則會下載下來的圖片打不開 res.on("data", function(chunk) { imgData += chunk; }); res.on("end", function() { var d = new Date(); fs.writeFile("./downImgs/" + Math.floor(Math.random() * 10000000) + '.jpg', imgData, "binary", function(err) { if (err) { console.log(err); } console.log("down success"); }); }); }); } exports.start = start;
最后index.js
var server = require("./server"); server.start();
說明
- 引入必須的模塊,http, cheerio, fs
- downloadPage函數(shù)接收URL,并在回調里處理數(shù)據(jù)。
- start函數(shù)里,定義url數(shù)據(jù)源,這里用的是騰訊動漫.
- for循環(huán)處理url數(shù)據(jù)內容,里面的downloadImg函數(shù),即保存圖片到本地。
以上就是nodejs做個爬蟲爬取騰訊動漫內容簡單實現(xiàn)的詳細內容,更多關于nodejs爬蟲爬取騰訊動漫的資料請關注腳本之家其它相關文章!
相關文章
基于socket.io+express實現(xiàn)多房間聊天
本文給大家分享的是使用node.js,基于socket.io+express實現(xiàn)多房間聊天的代碼,非常的實用,有需要的小伙伴可以來參考下2016-03-03干凈卸載Windows的Node.js環(huán)境的方法
這篇文章主要介紹了如何干凈卸載Windows的Node.js環(huán)境的方法,文中通過圖文結合的方式講解的非常詳細,對大家刪除Node.js環(huán)境有一定的幫助,需要的朋友可以參考下2025-01-01