一,使用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();
})
}
最终结果如图所示