cheerio数据抓取

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

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

1 npm install cheerio

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

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

 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.jsnpm

1 node print.js

数据获取成功:ui

相关文章
相关标签/搜索