<p>Node使用100行代碼實現(xiàn)抓取某用戶最新內(nèi)容且發(fā)送提醒杠输,主要使用了superagent 赎败,
cheerio,nodemailer蠢甲,node-schedule四個模塊代碼如下螟够,修改相關配置信息即可運行。
</p>
let request = require('superagent');
let cheerio = require('cheerio');
let nodemailer = require('nodemailer');
let schedule = require('node-schedule');
//UID獲取可在想抓取的新浪微博用戶首頁查看源代碼獲得
//修改uid
let reqUrl = 'http://service.weibo.com/widget/widget_blog.php?uid=你要抓取的用戶UID數(shù)字';
let oldVal;
let newVal;
//郵件服務器配置信息
let transport = nodemailer.createTransport({
//相關郵件服務器配置可在https://nodemailer.com/about/ 查看
service: 'qq',//qq郵箱
auth: {
user: '發(fā)件郵箱賬戶',
pass: '密碼'
}
});
//郵件發(fā)送配置選項
var options = {
from: '發(fā)件郵箱賬戶',
to: '目標賬戶',
subject: '郵件主題峡钓!',
text: '郵件內(nèi)容'
};
function requestUrl(url) {
//獲得微博信息
return request.get(url).then((res) => {
var $ = cheerio.load(res.text);
//內(nèi)容
var msgcontent = [];
$('.wgtCell .wgtCell_con').each(function(index, dom) {
var msg = {};
msg.inner = $(this).find('.wgtCell_txt').text();
msg.timer = $(this).find('.wgtCell_tm').text();
msgcontent.push(msg);
});
console.log('最新微博:' + msgcontent[0].inner + ':' + msgcontent[0].timer);
return msgcontent
})
};
function tasks(url, ms, to) {
//url 完整請求地址
//ms 每分鐘第幾秒開始任務
//to 目標郵箱,接受郵件提醒的郵箱地址
//獲取任務啟動時初始微博
requestUrl(url).then(res => { oldVal = res[0].inner });
//定時任務獲取新微博
schedule.scheduleJob({ second: ms }, () => {
console.log('任務運行于:' + new Date());
requestUrl(url).then(res => {
//獲得最新微博并且于初始值比對
newVal = res[0].inner;
if (oldVal != newVal) {
//修改發(fā)送郵件配置項
options.to = to;
options.text = '你關注人發(fā)了微博:' + newVal + '于:' + res[0].timer;
transport.sendMail(options, function(error, info) {
if (error) {
console.log('發(fā)送失斎艉印能岩!' + error)
} else {
console.log('發(fā)送成功!' + to);
//發(fā)送郵件成功則重置初始微博
requestUrl(url).then(res => { oldVal = res[0].inner });
}
})
} else {
console.log('微博未更新萧福!')
}
});
})
}
tasks('完整請求地址', '第幾秒啟動', '目標郵箱')