使用 Python 编写网页监控脚本,实时监测指定字段变化并 Telegram 通知

本脚本使用 Python 编写,每隔 3 分钟监控指定网页的特定字段,当字段值发生变化时,通过 Telegram 发送通知消息。

代码示例

import time
import requests
from telegram import Bot

# 设置网页地址和监控字段
url = 'http://example.com'
field_name = 'example_field'

# 设置 Telegram bot 的 token 和 chat_id
bot_token = 'your_bot_token'
chat_id = 'your_chat_id'

# 创建 Telegram bot 对象
bot = Bot(token=bot_token)

# 初始化前一次的字段值
pre_value = None

while True:
    # 请求网页内容
    response = requests.get(url)
    if response.status_code == 200:
        # 解析网页内容,获取指定字段的值
        content = response.content.decode('utf-8')
        field_value = content.split(field_name)[1].split('<')[0].strip()

        # 如果字段值发生变化,发送 Telegram 消息
        if pre_value is None:
            pre_value = field_value
        elif pre_value != field_value:
            bot.send_message(chat_id=chat_id, text=f'字段 {field_name} 的值已经变为 {field_value}!')

        pre_value = field_value

    # 等待 3 分钟再次监控
    time.sleep(180)

使用说明

  1. 安装库: 使用 pip install requests python-telegram-bot 安装必要的库。
  2. 设置参数:
    • url 替换为需要监控的网页地址。
    • field_name 替换为需要监控的字段名称。
    • bot_token 替换为你的 Telegram bot 的 token。
    • chat_id 替换为你的 Telegram 聊天 ID。
  3. 运行脚本: 运行脚本后,程序将每隔 3 分钟监控一次网页,当字段值发生变化时,会向你的 Telegram 发送通知消息。

注意

  • 实际情况中需要根据具体网页的结构和字段名称进行修改。
  • 在使用 Telegram bot 时需要先创建一个 bot 并获取其 token 和 chat_id。

总结

本脚本提供了简单的网页监控功能,可以方便地监测网页特定字段的变化,并及时通过 Telegram 通知用户。你可以根据实际需求修改脚本参数和功能,实现更加复杂的监控需求。

Python 网页监控脚本:实时监测指定字段变化并 Telegram 通知

原文地址: https://www.cveoy.top/t/topic/odzW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录