Python + Selenium 实现电商价格监控方案

核心原理

通过 Selenium 自动化浏览器模拟用户操作,定时抓取目标商品页面,解析价格数据并触发预警机制。技术框架如下: $$ \text{网页访问} \rightarrow \text{元素定位} \rightarrow \text{数据解析} \rightarrow \text{存储/预警} $$

实现步骤
  1. 环境配置

    • 安装依赖库:
      pip install selenium pandas schedule
      

    • 下载对应浏览器驱动(如 ChromeDriver)
  2. 基础监控脚本

from selenium import webdriver
from selenium.webdriver.common.by import By
import time, re

def monitor_price(url, interval=3600):
    # 初始化浏览器
    driver = webdriver.Chrome()
    driver.get(url)
    
    while True:
        try:
            # 定位价格元素(需根据目标网站调整选择器)
            price_element = driver.find_element(By.CSS_SELECTOR, ".product-price")
            price_text = price_element.text
            
            # 提取数字价格
            price = float(re.search(r'[\d,]+\.?\d*', price_text).group().replace(',', ''))
            print(f"{time.strftime('%Y-%m-%d %H:%M')} 当前价格: ¥{price:.2f}")
            
            # 价格异常检测(示例:低于历史最低价10%)
            if price < historical_low * 0.9:
                send_alert(f"价格异常下跌!当前价: ¥{price}")
                
        except Exception as e:
            print(f"抓取失败: {str(e)}")
        
        time.sleep(interval)  # 间隔时间
        driver.refresh()      # 刷新页面

# 示例使用
monitor_price("https://www.example.com/product/123")

  1. 关键优化技术

    • 动态等待:避免因网络延迟导致定位失败
      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.support import expected_conditions as EC
      
      element = WebDriverWait(driver, 10).until(
          EC.presence_of_element_located((By.ID, "priceBlock"))
      )
      

    • 反检测策略
      options = webdriver.ChromeOptions()
      options.add_argument("--disable-blink-features=AutomationControlled")
      options.add_experimental_option("excludeSwitches", ["enable-automation"])
      

    • 多商品监控:使用配置文件管理监控列表
      [
        {"name": "iPhone14", "url": "https://...", "threshold": 5000},
        {"name": "PS5", "url": "https://...", "threshold": 3000}
      ]
      

  2. 数据存储与分析

    import pandas as pd
    
    def save_price_data(product, price):
        df = pd.read_csv("price_history.csv")
        new_row = {"timestamp": time.time(), "product": product, "price": price}
        df = pd.concat([df, pd.DataFrame([new_row])])
        df.to_csv("price_history.csv", index=False)
    
    # 生成价格趋势图
    df.plot(x="timestamp", y="price", title="价格波动趋势")
    

  3. 预警通知实现

    import smtplib
    
    def send_alert(message):
        # 邮件通知配置
        sender = "monitor@example.com"
        receivers = ["user@example.com"]
        
        smtp_obj = smtplib.SMTP('smtp.example.com', 587)
        smtp_obj.starttls()
        smtp_obj.login("user", "password")
        smtp_obj.sendmail(sender, receivers, f"Subject: 价格警报\n\n{message}")
    

注意事项
  1. 法律合规性

    • 遵守目标网站 robots.txt 协议
    • 设置合理抓取频率(建议 >30分钟/次)
    • 仅用于个人用途
  2. 反爬应对

    • 使用代理 IP 轮换
    • 随机化操作间隔时间
    • 模拟人类操作轨迹
      from selenium.webdriver.common.action_chains import ActionChains
      actions = ActionChains(driver)
      actions.move_to_element(element).perform()
      

  3. 部署建议

    • 使用无头模式节省资源
      options.add_argument("--headless")
      

    • 设置系统定时任务(Linux cron / Windows Task Scheduler)
    • 云服务器部署(避免本地网络中断)

实际应用中需根据目标电商平台页面结构调整元素定位策略,建议先使用浏览器开发者工具分析页面 DOM 结构。完整项目可加入异常重试机制、日志记录等功能增强稳定性。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐