【nodeJs】用cheerio写一个爬虫吧

本是古典 何须时尚 2022-05-24 12:40 379阅读 0赞
  • 爬取Cnode社区的文章
  • 用到的模块:express cheerio superagent
  • superagent(http://visionmedia.github.io/superagent/ ) 是个 http 方面的库,可以发起 get 或 post 请求。
  • cheerio(https://github.com/cheeriojs/cheerio ) 大家可以理解成一个 Node.js 版的 jquery,用来从网页中以 css selector 取数据,使用方式跟 jquery 一样一样的。
  • cheerio中文API:https://blog.csdn.net/ac_greener/article/details/80469446

代码app.js:

  1. var express = require('express');
  2. var app = express();
  3. var superagent = require('superagent');
  4. var cheerio = require('cheerio');
  5. app.get('/', function (req, res) {
  6. superagent.get('https://cnodejs.org/')
  7. .end(function (err, sres) {
  8. if (err) {
  9. return err;
  10. }
  11. var $ = cheerio.load(sres.text);
  12. var items = [];
  13. $('#topic_list .topic_title').each(function (index, element) {
  14. var $element = $(element);
  15. items.push({
  16. title: $element.attr('title'),
  17. href: $element.attr('href')
  18. });
  19. });
  20. res.send(items);
  21. })
  22. });
  23. app.listen('3000', function () {
  24. console.log('server start at localhost:3000');
  25. });
  26. 然后执行:node app.js,再去访问localhost3000就可以看到结果了

这里写图片描述

发表评论

表情:
评论列表 (有 0 条评论,379人围观)

还没有评论,来说两句吧...

相关阅读

    相关 python一个爬虫

    可以使用 Python 的第三方库 `requests` 和 `BeautifulSoup` 来编写一个爬虫。 首先,需要安装这两个库,可以使用 `pip` 命令来安装: