cheerio数据抓取

    很多语言都能写个爬虫抓取数据,js自然也可以,使用cheerio可以支持css检索,较快捷的获取需要的数据。首先,先把node.js给安装了。可到官网下载。安装好node.js后,使用npm安装cheerio。

    我这里使用的是win7,可以在 node.js command prompt 里输入

1 npm install cheerio

要注意的是,到项目所在的目录下执行。

     接着就可以开发了,使用node.js http模块并引入cheerio模块,使用get方式获取待抓取的网页内容,具体的解析可以参考https://github.com/cheeriojs/cheerio;

 1 var url = "http://www.baidu.com/s?rtt=2&tn=baiduwb&rn=20&cl=2&wd=%BA%A3%D4%F4%CD%F5"
 2 var http = require("http");
 3 // Utility function that downloads a URL and invokes
 4 // callback with the data.
 5 function download(url, callback) {
 6     http.get(url, function(res) {
 7         var data = "";
 8         res.on('data', function(chunk) {
 9             data += chunk;
10         });
11         res.on("end", function() {
12             callback(data);
13         });
14     }).on("error", function() {
15         callback(null);
16     });
17 }
18 var cheerio = require("cheerio");
19 download(url, function(data) {
20     if (data) {
21         var $ = cheerio.load(data);
22         //id为weibo里的所有li,每个li里的段落p的内容 
23         $('#weibo').find('li').each(function(i, elem) {
24             console.log($(this).find('p').text());
25             console.log(" ");
26         })
27     }
28     else
29         console.log("error");
30 });

保存为print.js,运行命令执行print.js

1 node print.js

数据获取成功:

posted on 2014-06-04 18:34  d&lufd  阅读(1447)  评论(0编辑  收藏  举报

导航