nodejs 30行代码 爬豆瓣电影数据
生活随笔
收集整理的這篇文章主要介紹了
nodejs 30行代码 爬豆瓣电影数据
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
##用nodejs 寫(xiě)爬蟲(chóng) 關(guān)鍵模塊:cheerio、http,request。 consonl.log() 出來(lái)的數(shù)據(jù)
首先安裝相關(guān)的模塊:
//我用了某寶的鏡像安裝 原來(lái)是 npm,-g 可以根據(jù)自己情況是全局按裝還是局域安裝 cnpm install -g jquerycnpm install -g cheeriocnpm install requestcnpm install http ......復(fù)制代碼根據(jù)你需要用的的模塊安裝 代碼如下:
// 新建一個(gè)對(duì)象 var MyUtil = function () { }; // var $ = require('../node_modules/jQuery'); var request = require('request'); // 用于 保存body的html數(shù)據(jù) var bodtTemp; MyUtil.prototype.get=function(url,callback){// console.log("MyUtil.prototype") // 打印request(url, function (error, response, body) {if (!error && response.statusCode == 200) {// console.log(body) // 打印目標(biāo)頁(yè)面console.log("request ");// 用臨時(shí)變量保存起來(lái)請(qǐng)求回來(lái)的body數(shù)據(jù)bodtTemp=body;var movie={} // movie.name = $(body).find('span[property="v:itemreviewed"]').text();// movie.director = $(body).find('#info span:nth-child(1) a').text();}}) } // console.log(movie); //獲取目標(biāo)網(wǎng)頁(yè)的數(shù)據(jù) var temp = new MyUtil(); var httpUrl='https://movie.douban.com/subject/25921812/?tag=%E7%83%AD%E9%97%A8&from=gaia_video'; // var httpUrl='http://movie.douban.com/subject/1152952'; temp.get(httpUrl); console.log('bodtTemp is '+bodtTemp); // 開(kāi)啟自己的http服務(wù)器 var http = require('http') http.createServer(function(req,res){res.writeHead(200,{'Content-Type':'text/html'});// res.write(bodtTemp);let cheerio = require('cheerio')let $ = cheerio.load(bodtTemp)// $('h2.title').text('Hello there!')// $('h2').addClass('welcome')// $('#db-nav-movie .nav-logo a').text("哈哈")// $("#dale_movie_subject_bottom_super_banner_frame").remove();// 移除 id 里面的內(nèi)容// $("#footer").remove();console.log($('#info').text());// $.html()// console.log($.html());res.write($.html());// res.end('<p>結(jié)束</p>');res.end(); }).listen(5858);復(fù)制代碼保存為index.js 文件,切換到 你的文件路徑,用node 命令打開(kāi): 如:
node index.js 復(fù)制代碼瀏覽器打開(kāi)
http://127.0.0.1:5858/ 復(fù)制代碼**記得要打開(kāi)瀏覽器訪(fǎng)問(wèn)地址才能看到控制臺(tái)的數(shù)據(jù)。 ###本文為了更好閱讀以及新手可以直接執(zhí)行,提高新手興趣,故把所有可執(zhí)行代碼直接放一個(gè)文件,詳細(xì)以及一些測(cè)試也有備注。嘗試去修改一下要爬的鏈接以及代碼吧,一切都是實(shí)踐中的出效果。
轉(zhuǎn)載于:https://juejin.im/post/5a3217baf265da4310486603
總結(jié)
以上是生活随笔為你收集整理的nodejs 30行代码 爬豆瓣电影数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: quartus-ModeliSm仿真教程
- 下一篇: appinfo.json