
正文
cheerio数据抓取
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
很多语言都能写个爬虫抓取数据,js自然也可以,使用cheerio可以支持css检索,较快捷的获取需要的数据。首先,先把node.js给安装了。可到官网下载。安装好node.js后,使用npm安装cheerio。
我这里使用的是win7,可以在 node.js command prompt 里输入
npm install cheerio
要注意的是,到项目所在的目录下执行。
接着就可以开发了,使用node.js http模块并引入cheerio模块,使用get方式获取待抓取的网页内容,具体的解析可以参考https://github.com/cheeriojs/cheerio;
var url = "http://www.baidu.com/s?rtt=2&tn=baiduwb&rn=20&cl=2&wd=%BA%A3%D4%F4%CD%F5"
var http = require("http");
// Utility function that downloads a URL and invokes
// callback with the data.
function download(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);
});
}
var cheerio = require("cheerio");
download(url, function(data) {
if (data) {
var $ = cheerio.load(data);
//id为weibo里的所有li,每个li里的段落p的内容
$('#weibo').find('li').each(function(i, elem) {
console.log($(this).find('p').text());
console.log(" ");
})
}
else
console.log("error");
});
保存为print.js,运行命令执行print.js
node print.js
数据获取成功:







