Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用node.js来实现简单爬虫 #125

Open
kvkens opened this issue Aug 28, 2016 · 0 comments
Open

使用node.js来实现简单爬虫 #125

kvkens opened this issue Aug 28, 2016 · 0 comments

Comments

@kvkens
Copy link
Member

kvkens commented Aug 28, 2016

最近因为工作中使用node.js来开发工具,所以想到了分享下之前写的简单爬虫!

目的

  • superagent 抓取网页
  • cheerio 分析网页

准备

  • Node.js
  • Express
  • Superagent
  • Cheerio

文档参考

具体编码

这里我就拿正妹的博客做演示了……

var express = require('express');
var superagent = require('superagent');
var cheerio = require('cheerio');

var app = express();
app.get('/', function (req, res, next) {
    superagent.get('http://www.cnblogs.com/rubylouvre/')
        .end(function (err, sres) {
            if (err) {
                return next(err);
            }
            // sres.text 里面存储着网页的 html 内容,将它传给 cheerio.load 之后
            // 就可以得到一个实现了 jquery 接口的变量,我们习惯性地将它命名为 `$`
            // 剩下就都是 jquery 的内容了
            var $ = cheerio.load(sres.text);
            var items = [];
            $("#main > .post h2 > a").each(function (index, element) {
                var $element = $(element);
                items.push({
                    "title": $(this).text(),
                    "url": $(this).attr("href")
                });
            });
            res.send(items);
        });
});

app.listen(4000, function () {
    console.log('app is listenling at port 4000');
});

是不是非常简单,这个只是最初级的爬虫,一般复杂的需要匹配正则筛选主要的数据进行入库如MongoDB等,不同层级、翻页爬数据这才是一个合格的爬虫。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant