如果我们想:不是每次都打开json文件,导入到数据库,而是直接能把获取的数据写入到数据库,开发时直接使用,是不是方便多了。这里很好的解决了这个问题。
本程序在上一篇文章简易的爬虫程序中的程序依赖中增加mongoose
包,请自行创建node项目并安装,推荐使用webstorm直接创建一个node.js express App。
mongoose操作MongoDB更多强大功能参考官文:https://mongoosejs.com/
mongoose操作MongoDB模式:通过创建Schema模型去匹配数据库中的数据,返回的数据结果通过mongoose提供的方法进行操作。
1.引入依赖模块
1 2 3 4 5 6 7 8 9
| const http = require("http"); const path = require("path"); const url = require("url"); const fs = require("fs");
const mongoose = require("mongoose"); const superagent = require("superagent"); const cheerio = require("cheerio");
|
2.连接数据库,建数据模型
推荐使用MongoDB可视化工具Studio 3T,安装MongoDB数据库自行参考网上资料。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| var mongourl = 'mongodb://localhost/DBBook'; mongoose.connect(mongourl); var Schema = mongoose.Schema;
var newBookSchema = new Schema({ title: String, bookId: Number, grade: Number, bookInfo: String, bookImg: String, description: String }); var NewBook = mongoose.model('NewBook', newBookSchema, 'newbooks');
|
3.调用superagent的get方法和end方法处理
get(): 此方法参数为获取数据的链接
end(): 此方法第一的参数为error对象,第二个参数为get中页面的所有DOM结果
1 2 3 4 5
| superagent .get("https://book.douban.com/latest?icn=index-latestbook-all") .end((error, response)=>{ })
|
4.分析结构,提取相应的数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| var content = response.text;
var $ = cheerio.load(content);
var result = [];
$(".cover-col-4 li").each(function(index,value){
var address = $(value).find(".cover").attr("href"); var bookId = address.replace(/[^0-9]/ig,"");
var gradeStr = $(value).find(".detail-frame .rating .font-small").text().replace(/\ +/g,"").replace(/[\r\n]/g,"");
var oneBook = { title: $(value).find(".detail-frame h2 a").text(), bookId: bookId, grade: Number(gradeStr) ? Number(gradeStr) : 0, bookInfo: $(value).find(".detail-frame .color-gray").text().replace(/\ +/g,"").replace(/[\r\n]/g,""), bookImg: $(value).find(".cover img").attr("src").replace(/^https:/g,""), description: $(value).find(".detail-frame .detail").text().replace(/\ +/g,"").replace(/[\r\n]/g,"") }; result.push(oneBook); var newBook = new NewBook(oneBook);
newBook.save(function(err){ if(err){ console.log('保存失败:'+ err); return; } console.log("OK!"); }); });
|
完整代码请参考:https://github.com/joydezhong/SimpleCrawler/blob/master/crawler.js