
本文介绍如何在无官方 api 的前提下,通过服务端定时抓取与智能比对,实现对股票等动态网页数据的持续监控,并在价格突破阈值时触发通知——全程无需本地设备参与,适合初学者快速落地。
本文介绍如何在无官方 api 的前提下,通过服务端定时抓取与智能比对,实现对股票等动态网页数据的持续监控,并在价格突破阈值时触发通知——全程无需本地设备参与,适合初学者快速落地。
在缺乏官方 API 的场景下(例如印度股市行情页),实时价格监控的核心思路是:服务端主动轮询 + HTML 内容解析 + 差异检测 + 条件告警。整个流程必须脱离用户终端,完全运行于远程服务器,确保 7×24 小时稳定执行。
✅ 推荐技术栈(新手友好型)
- 语言:Python(生态丰富、语法简洁,requests + BeautifulSoup + schedule 即可开箱即用)
- 调度:APScheduler(纯 Python,支持内存级定时任务)或系统级 cron(更稳定,推荐生产环境)
- 存储与状态:轻量级文件(如 JSON)记录上一次价格,避免重复告警
- 通知方式:邮件(smtplib)、Telegram Bot(HTTP API)、或 Webhook(推送至 Slack/钉钉)
? 示例代码(Python 实现)
以下是一个完整可运行的监控脚本(保存为 monitor_stock.py):
import requests
from bs4 import BeautifulSoup
import json
import time
from datetime import datetime
# 配置项(请替换为实际目标网页与选择器)
TARGET_URL = "https://example-stock-site.in/live/tata-motors"
PRICE_SELECTOR = "#stock-price" # 使用浏览器开发者工具定位价格元素的 CSS 选择器
ALERT_THRESHOLD = 850.0 # 触发告警的价格阈值(单位:INR)
STATE_FILE = "last_price.json"
def get_current_price():
try:
headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"}
resp = requests.get(TARGET_URL, headers=headers, timeout=10)
resp.raise_for_status()
soup = BeautifulSoup(resp.text, "html.parser")
price_elem = soup.select_one(PRICE_SELECTOR)
if not price_elem:
raise ValueError("Price element not found")
price_text = price_elem.get_text(strip=True).replace(",", "").replace("₹", "")
return float(price_text)
except Exception as e:
print(f"[{datetime.now()}] 抓取失败: {e}")
return None
def load_last_price():
try:
with open(STATE_FILE, "r") as f:
return json.load(f).get("price")
except (FileNotFoundError, json.JSONDecodeError):
return None
def save_last_price(price):
with open(STATE_FILE, "w") as f:
json.dump({"price": price, "updated_at": datetime.now().isoformat()}, f)
def check_and_alert():
current = get_current_price()
if current is None:
return
last = load_last_price()
# 仅当价格首次超过阈值时告警(避免连续刷屏)
if last is None or current > ALERT_THRESHOLD > last:
print(f"[{datetime.now()}] ⚠️ 价格突破!当前价:₹{current:.2f}(阈值:₹{ALERT_THRESHOLD})")
# 此处插入通知逻辑,例如:
# send_telegram_alert(f"? Tata Motors 突破 ₹{current:.2f}!")
save_last_price(current)
# 手动测试调用
if __name__ == "__main__":
check_and_alert()⚙️ 部署到服务器(Linux 示例)
- 安装依赖:
pip3 install requests beautifulsoup4
- 设置每 10 秒执行一次(使用 cron):
# 编辑 crontab crontab -e # 添加一行(每10秒太密,建议至少30秒起;cron 最小粒度为1分钟,故用循环脚本) * * * * * /usr/bin/python3 /path/to/monitor_stock.py >> /var/log/stock-monitor.log 2>&1
✅ 更优实践:改用 systemd timer 或 APScheduler 启动守护进程,支持 sub-minute 间隔。
⚠️ 关键注意事项
- 反爬策略:目标网站可能封禁频繁请求。务必添加 User-Agent、合理设置 time.sleep()、必要时使用代理池或浏览器自动化(如 Playwright)。
- HTML 结构稳定性:价格元素的 ID/Class 可能随网站改版失效。建议定期人工验证选择器,并加入异常日志。
- 告警去重:示例中采用「仅当价格从下方穿越阈值时触发」,避免同一条件反复通知。
- 服务器资源:长期运行需考虑内存泄漏(尤其使用 Playwright 时),建议进程级守护(systemd 或 supervisord)。
- 法律与合规:确认目标网站 robots.txt 允许抓取,且不违反其服务条款;高频请求可能构成滥用,应控制频率并尊重 Crawl-Delay。
掌握这一模式后,你不仅能监控股价,还可扩展至航班状态、竞品价格、政策公告等任意公开网页数据源。核心不变:可靠获取 → 精准提取 → 智能判断 → 可靠通知。从一个脚本开始,逐步加固健壮性,便是服务端数据监控工程师的成长起点。










