如何使用Selenium Python监控页面元素文本变化并推送Discord通知
解决方案
要实现指定页面元素的文本变化监控并触发Discord通知,核心思路是保存初始文本作为基准,定时重新获取文本并对比,发现差异时发送通知。以下是具体实现方案和完整代码:
关键步骤拆解
- 基准文本存储:先获取目标元素的初始文本,作为后续对比的基准值
- 循环检测逻辑:用循环定时重新获取元素文本,和基准值做比对
- Discord通知:通过Discord Webhook发送变化提醒,无需复杂权限配置
- 稳定性优化:替换原代码中的
sleep()为Selenium显式等待,避免页面加载延迟导致的异常
完整代码实现
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import requests import time # Discord Webhook URL(替换成你自己的) DISCORD_WEBHOOK_URL = "你的Discord Webhook链接" def send_discord_notification(message): """发送消息到Discord""" data = {"content": message} try: requests.post(DISCORD_WEBHOOK_URL, json=data) print("通知已发送到Discord") except Exception as e: print(f"发送通知失败: {str(e)}") def monitor_element_text(): # 初始化浏览器 option = webdriver.ChromeOptions() # 可选:添加无头模式,后台运行 # option.add_argument("--headless=new") driver = webdriver.Chrome(executable_path=r"ChromePath", options=option) try: # 打开目标网站并完成初始操作 driver.get("Mywebsite") # 等待链接元素加载并点击 link = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, 'xpath goes here')) ) link.click() # 等待输入框加载并输入内容 search_input = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, 'name')) ) search_input.send_keys("what im searching for") # 等待按钮加载并点击 search_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, "name")) ) search_button.click() # 获取初始元素文本作为基准 target_element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH, 'xpath goes here')) ) previous_text = target_element.text print(f"初始文本: {previous_text}") # 开始循环监控 while True: # 重新获取元素文本 current_text = target_element.text # 对比文本是否变化 if current_text != previous_text: message = f"⚠️ 元素文本发生变化!\n原文本: {previous_text}\n新文本: {current_text}" send_discord_notification(message) # 更新基准文本,继续监控后续变化 previous_text = current_text # 间隔一段时间再检测(这里设为30秒,可根据需求调整) time.sleep(30) except Exception as e: print(f"监控过程中出现异常: {str(e)}") finally: # 关闭浏览器(如果是无头模式可以不用,但最好加上) driver.quit() if __name__ == "__main__": monitor_element_text()
注意事项
- Discord Webhook获取:打开Discord服务器设置→集成→Webhooks→新建Webhook,复制生成的URL替换代码中的
DISCORD_WEBHOOK_URL - 检测间隔:
time.sleep(30)控制检测频率,根据需求调整,不要过于频繁避免被网站反爬 - 异常处理:代码中加入了基础异常捕获,可根据需要扩展(比如元素消失后的重试逻辑)
- 无头模式:如果不需要浏览器界面,可开启
--headless=new参数,减少资源占用
内容的提问来源于stack exchange,提问作者kidlo22
相关产品推荐
相关产品推荐

