乐于分享
好东西不私藏

AI 助手 + Puppeteer:3 步搭建你的网页监控机器人

AI 助手 + Puppeteer:3 步搭建你的网页监控机器人

告别手动刷新,让 AI 帮你盯住网页变化 📡

一、为什么需要网页监控?

每天你可能都要反复做这些事:

• 🔍 刷好几次官网看有没有新公告

• 🛒 盯着商品页等降价

• 📢 蹲守活动页面抢名额

• 📰 定时检查行业资讯有没有更新

手动刷新又累又容易漏,网页监控机器人可以帮你自动巡逻、实时通知,有变化第一时间告诉你。

二、核心工具介绍

Puppeteer 是什么?

Puppeteer 是 Google 推出的浏览器自动化库,基于 Chrome DevTools Protocol,可以:

• 🌐 启动无头浏览器访问任意网页

• 👀 监听页面内容变化

• 📸 截图保存历史状态

• 📬 检测到变化后推送通知

类比理解: 就像雇了一个 24 小时在岗的"盯梢员",每隔几分钟帮你去看一眼页面,有变化立刻报告。

三、环境准备

1. 安装 Node.js

访问  下载 LTS 版本。

验证安装:

node -v

npm -v2. 创建项目

# 创建项目目录

mkdir web-watcher

cd web-watcher

# 初始化项目

npm init -y

# 安装 Puppeteer

npm install puppeteer

# 安装额外工具

npm install node-notifier  # 桌面通知3. 目录结构

web-watcher/

├── watchers/

│   ├── price-watch.js    # 价格监控

│   └── content-watch.js  # 内容变化监控

├── config/

│   └── targets.js        # 监控目标配置

├── state/                # 状态保存目录

│   └── snapshots/        # 页面快照

├── utils/

│   └── notifier.js       # 通知工具

└── run.js                # 主入口四、实战案例:商品价格监控

需求分析

假设你在盯某款产品,希望:

• 每隔 10 分钟检查一次价格

• 价格下降超过 5% 就通知你

• 保存历史价格记录

代码实现

1. 配置文件(config/targets.js)

module.exports = {

  targets: [

    {

      name: '某东商品',

      url: 'https://item.jd.com/100012345678.html',

      selector: '.price',  // 价格元素选择器

      checkInterval: 10 * 60 * 1000,  // 10分钟

      threshold: 0.05  // 降价5%触发通知

    }

  ]

};2. 监控脚本(watchers/price-watch.js)

const puppeteer = require('puppeteer');

const fs = require('fs');

const path = require('path');

const config = require('../config/targets');

// 读取上次记录的价格

function getLastPrice(targetName) {

  const filePath = path.join(__dirname, '../state', `${targetName}.json`);

  if (!fs.existsSync(filePath)) return null;

  return JSON.parse(fs.readFileSync(filePath, 'utf8'));

}

// 保存当前价格

function savePrice(targetName, price, timestamp) {

  const filePath = path.join(__dirname, '../state', `${targetName}.json`);

  fs.writeFileSync(filePath, JSON.stringify({ price, timestamp }));

}

// 发送通知

function notify(message) {

  console.log(`🔔 ${message}`);

  // 这里可以接入企业微信/钉钉/邮件通知

}

async function watchPrice(target) {

  const browser = await puppeteer.launch({

    headless: true,  // 无头模式,后台运行

    args: ['--no-sandbox']

  });

  try {

    const page = await browser.newPage();

    console.log(`📡 访问页面: ${target.name}`);

    await page.goto(target.url, { 

      waitUntil: 'networkidle2',

      timeout: 30000

    });

    // 等待价格元素加载

    await page.waitForSelector(target.selector, { timeout: 5000 });

    // 提取价格(去除非数字字符)

    const priceText = await page.$eval(target.selector, el => el.innerText);

    const currentPrice = parseFloat(priceText.replace(/[^\d.]/g, ''));

    console.log(`💰 当前价格: ¥${currentPrice}`);

    // 对比历史价格

    const lastRecord = getLastPrice(target.name);

    if (lastRecord) {

      const diff = (lastRecord.price - currentPrice) / lastRecord.price;

      if (diff >= target.threshold) {

        notify(`🎉 ${target.name} 降价啦!\n原价: ¥${lastRecord.price}\n现价: ¥${currentPrice}\n降幅: ${(diff * 100).toFixed(1)}%`);

      }

    }

    // 截图保存

    const screenshotPath = path.join(__dirname, '../state/snapshots', `${target.name}-${Date.now()}.png`);

    await page.screenshot({ path: screenshotPath });

    // 保存记录

    savePrice(target.name, currentPrice, new Date().toISOString());

  } catch (error) {

    console.error(`❌ 监控失败: ${error.message}`);

  } finally {

    await browser.close();

  }

}

// 启动监控循环

config.targets.forEach(target => {

  watchPrice(target);

  setInterval(() => watchPrice(target), target.checkInterval);

});3. 主入口(run.js)

const priceWatcher = require('./watchers/price-watch');

console.log('🚀 网页监控机器人已启动!');

console.log('按 Ctrl+C 停止监控');五、使用方法

基础运行

# 启动监控

node run.js后台持续运行

# 使用 pm2 守护进程

npm install -g pm2

pm2 start run.js --name web-watcher

pm2 logs web-watcher扩展:接入企业微信通知

const axios = require('axios');

function sendWechatNotify(message) {

  axios.post('https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=YOUR_KEY', {

    msgtype: 'text',

    text: { content: message }

  });

}六、进阶技巧

1. 防被封策略

// 随机延迟,模拟人工访问

await page.waitForTimeout(Math.random() * 3000 + 2000);

// 设置 User-Agent

await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36...');2. 监控内容变化(非价格)

// 提取页面文本内容做对比

const content = await page.$eval('body', el => el.innerText);

const hash = require('crypto').createHash('md5').update(content).digest('hex');

if (lastHash !== hash) {

  notify('📢 页面内容发生变化!');

}3. 多目标并发监控

const { throttle } = require('lodash');

// 限制并发数,避免被封

const limitedWatch = throttle(watchPrice, 5000);

config.targets.forEach(target => limitedWatch(target));七、注意事项

⚠️ 使用提醒

• 遵守目标网站的 robots.txt 和访问频率限制

• 不要监控需要登录的私密页面

• 价格数据仅作参考,以实际购买页面为准

• 定期检查脚本是否因页面改版而失效

🔧 调试建议

// 开发阶段用有头模式,方便观察

const browser = await puppeteer.launch({

  headless: false,  // 显示浏览器

  slowMo: 250       // 减慢操作速度

});八、总结

通过本文,你学会了:

• ✅ 使用 Puppeteer 自动化访问网页

• ✅ 实现价格监控和变化检测

• ✅ 设置定时任务和通知推送

• ✅ 掌握防封策略和调试技巧

下一步可以尝试:

• 监控多个商品,做价格对比

• 接入钉钉/飞书做团队通知

• 把监控数据存数据库,画价格趋势图

• 结合 AI 分析页面内容变化

把盯屏幕的活儿交给机器人,把注意力留给更重要的事 😊

有问题欢迎留言

相关学习资料