Paste_Image.png
用nodejs 寫爬蟲
關鍵模塊:cheerio、http,request。
consonl.log() 出來的數據
Paste_Image.png
首先安裝相關的模塊:
//我用了某寶的鏡像安裝 原來是 npm,-g 可以根據自己情況是全局按裝還是局域安裝
cnpm install -g jquery
cnpm install -g cheerio
cnpm install request
cnpm install http
......
根據你需要用的的模塊安裝
代碼如下:
// 新建一個對象
var MyUtil = function () {
};
// var $ = require('../node_modules/jQuery');
var request = require('request');
// 用于 保存body的html數據
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) // 打印目標頁面
console.log("request ");
// 用臨時變量保存起來請求回來的body數據
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);
//獲取目標網頁的數據
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);
// 開啟自己的http服務器
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 里面的內容
// $("#footer").remove();
console.log($('#info').text());
// $.html()
// console.log($.html());
res.write($.html());
// res.end('<p>結束</p>');
res.end();
}).listen(5858);
保存為index.js 文件,切換到 你的文件路徑,用node 命令打開:
如:
node index.js
瀏覽器打開
http://127.0.0.1:5858/
**記得要打開瀏覽器訪問地址才能看到控制臺的數據。