nodejs 学习代码笔记

一,使用cheerio 爬取慕课网视频信息

cheerio 的用法感觉跟jquery挺像的,因此可以先在浏览器上通过jquery来获取元素信息,然后再把代码搞进来即可。

const request = require('request');
var fs = require('fs');
const cheerio = require('cheerio');
const { eq } = require('cheerio/lib/api/traversing');

const url = 'http://www.imooc.com/learn/857'; // 需要爬取的页面地址

const videocrawler = (url) => {
  return new Promise((resolve, reject) => {
    request(url, (err, res) => {
      const $ = cheerio.load(res.body.toString()); // 利用cheerio对页面进行解析
      const videoList = [];
      $('.video li a').each((index) => {
        const $node = $('.video li a').eq(index); // 遍历并获取每一个元素
        const $nodeText = $node.text().trim();
        const text = $(this).text().trim().split('\n');
        const titlePattern = /^\d+.*[mp4]?/;
        const timePattern = /\((\d+\:\d+)\)/;
        const item = {
          title: $node.parent().parent().parent().text().trim().split('\n')[0],
          url: 'http://www.imooc.com' + $node.attr('href'),
          name: $nodeText.match(titlePattern)[0],
          duration: $nodeText.match(timePattern)[0],
        }
        const s = item.url.match(/video\/(\d+)/);
        if (Array.isArray(s)) {
          item.id = s[1];
          videoList.push(item);
        }
        resolve(videoList);
      });
    });
  }).catch((err) => {
    reject(err);
  });
}

const saveFile = async() => {
  const videoList = await videocrawler(url);
  try {
    fs.writeFileSync('output.json', JSON.stringify(videoList, null, 2));
  } catch (error) {
    console.error(error);
  }
};
saveFile(); // 保存为本地的JSON文件

这里有个奇怪的点就是 each循环中 $(this) 获取不到当前遍历的子节点信息,因此通过eq方法来获取当前节点。有知道的大佬麻烦解疑下。

最终得到如图所示json文件
在这里插入图片描述

二,微信群机器人定时发送消息

首先获取需要发送的内容,然后调用企业微信的接口发送请求

const axios = require('axios');
const schedule = require('node-schedule');
const postZhihu = () => {
  axios.get('https://news-at.zhihu.com/api/4/news/latest')
    .then(res => {
      const stories = res.data.stories || [];
      postMessage(stories);
    }).catch(err => {
      console.log(err);
    })
};
// 获取知乎的最新日报
const postMessage = (stories) => {
  const articles = stories.map(story => ({
    "title": story.title,
    "url": story.url,
    "picurl": story.images[0]
  }));
  axios.post('https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXXXXXXXXXXXXXXX', {
    'msgtype': 'news',
    'news': {
      articles,
    }
  }).then(res => {
    console.log(res);
  }).catch(err => {
    console.error(err);
  })
};
// 每分钟 的 30秒自动执行一次
const scheduleCronstyle = () => {
  schedule.scheduleJob('30 * * * * *', () => {
    postZhihu();
  })
}

最终结果如图所示
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值