68 lines
2.0 KiB
TypeScript
68 lines
2.0 KiB
TypeScript
import puppeteer from 'puppeteer-core';
|
|
import config from "./config";
|
|
import db from "./db/index";
|
|
import mailer from "./utils/mailer";
|
|
import schedule from 'node-schedule';
|
|
|
|
// 把你的逻辑封装成函数
|
|
async function startTask() {
|
|
console.log('');
|
|
console.log('====================================');
|
|
console.log('⏰ 定时任务开始执行:', new Date().toLocaleString());
|
|
console.log('====================================');
|
|
console.log('');
|
|
|
|
try {
|
|
// 1. 启动无头浏览器
|
|
const browser = await puppeteer.launch(config.launchConfig);
|
|
const page = await browser.newPage();
|
|
await page.setExtraHTTPHeaders(config.httpHeaders);
|
|
|
|
// 访问页面
|
|
await page.goto(config.page, {
|
|
waitUntil: 'networkidle2',
|
|
timeout: <number>config.pageTimeOut
|
|
});
|
|
|
|
await page.setViewport({ width: 1080, height: 1024 });
|
|
|
|
// 抓取数量
|
|
const number = await page.$eval(
|
|
'#semiTabpost h2 span:last-child',
|
|
el => el.textContent.trim()
|
|
);
|
|
console.log('1 抓取到主播最新作品数:', number);
|
|
|
|
// 获取旧值
|
|
const { count } = await db.get();
|
|
console.log('2 数据库里的旧值:', count);
|
|
|
|
// 判断是否更新
|
|
if (String(count) !== String(number)) {
|
|
console.log('✅ 主播更新作品了');
|
|
await mailer.send();
|
|
await db.set({
|
|
count: number,
|
|
time: new Date().toLocaleString()
|
|
});
|
|
console.log('✅ 已更新到数据库');
|
|
} else {
|
|
console.log('❌ 主播没有更新作品');
|
|
}
|
|
|
|
await browser.close();
|
|
console.log('✅ 本次任务执行完成\n');
|
|
|
|
} catch (err) {
|
|
console.error('❌ 任务执行出错:', err);
|
|
}
|
|
}
|
|
|
|
|
|
console.log('✅ 程序已启动,执行任务,定时规则:', config.cron);
|
|
|
|
schedule.scheduleJob(config.cron, async () => {
|
|
await startTask();
|
|
});
|
|
|
|
// startTask()
|