【发布时间】:2016-06-24 13:02:45
【问题描述】:
我是 node js 和 mongodb 的新手。只是测试一些想法,所以我试图创建一个网络爬虫,将数据添加到 mongodb 的数据库中。我有一个连接到 mongodb 并通过节点 js 脚本将数据动态添加到数据库的脚本。我在控制台中运行这个脚本,如下所示:'node scrapeData.js' 脚本运行没有任何错误,但是当我启动 mongo shell 并运行 db.posts.find() 时,我得到 0 条记录。我知道我的脚本在控制台中记录数据数组时成功地抓取了数据。不知道我哪里错了。这是我的脚本:
var MongoClient = require('mongodb').MongoClient;
//requiring the module so we can access them later on
var request = require("request");
var cheerio = require("cheerio");
MongoClient.connect('mongodb://127.0.0.1:27017/mydb', function (err, db) {
if (err) {
throw err;
}
else {
console.log("successfully connected to the database");
//define url to download
var url = "http://www.nyxcosmetics.ca/en_CA/highlight-contour";
var prodList = [];
var priceList = [];
var products = [];
request(url, function(error, response, body) {
if(!error) {
//load page into cheerio
var $ = cheerio.load(body);
$(".product_tile_wrapper").each(function(i, elem) {
prodList[i] = $(this).find($(".product_name")).attr("title");
priceList[i] = $(this).find($(".product_price")).attr("data-pricevalue");
});
prodList.join(', ');
for(var i = 0; i < prodList.length; i++) {
var prod = {
name: prodList[i],
price: priceList[i]
};
products.push(prod);
}
console.log(products); //print the array of scraped data
//insert the prods into the database
//in the 'posts' collection
var collection = db.collection('posts');
collection.insert(products);
console.log("products inserted into posts collection");
//Locate all the entries using find
collection.find().toArray(function(err, results) {
console.log(results);
});
} else {
console.log("We've encountered an error!")
}
});
}
db.close();
});
【问题讨论】:
标签: javascript node.js mongodb