You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询:如何用Python对比Excel中对应产品价格并触发邮件通知?

产品价格变动对比逻辑实现方案

问题背景

我开发了一个Python程序,用于从Amazon和Chem Warehouse爬取产品名称(productName)和价格(productPrice),并将数据写入Excel表格。现在需要实现同一产品的价格对比逻辑,当价格发生变化时触发邮件提醒(邮件发送模块已自行实现,仅需价格对比部分的逻辑指导)。

Excel数据样例如下:

Date    Time    Item    Cost

October 16, 2022    02:26:50    Versace Man Eau Fraiche Eau de Toilette for Men, 100ml  69.99

October 16, 2022    02:26:54    Versace Man Eau Fraiche Eau de Toilette for Men, 100ml  69.99

October 16, 2022    15:33:55    Versace Man Eau Fraiche Eau de Toilette for Men, 100ml  69.99

October 16, 2022    15:33:55    Burberry London Fabric Eau De Parfum, 100ml 59

October 16, 2022    15:54:55    Versace Man Eau Fraiche Eau de Toilette for Men, 100ml  69.99   
October 16, 2022    15:54:55    Burberry London Fabric Eau De Parfum, 100ml 59  
October 16, 2022    16:10:40    Versace Man Eau Fraiche Eau de Toilette for Men, 100ml  69.99   
October 16, 2022    16:10:40    Burberry London Fabric Eau De Parfum, 100ml 59  

核心对比逻辑实现

1. 数据读取与预处理

优先使用pandas处理Excel数据,操作更高效:

import pandas as pd

# 读取Excel文件
df = pd.read_excel('price_tracker.xlsx')

# 数据清洗:确保产品名称无多余空格、统一大小写,价格转为数值型
df['Item'] = df['Item'].str.strip().str.lower()
df['Cost'] = pd.to_numeric(df['Cost'], errors='coerce')

2. 按产品分组并对比历史价格

将数据按产品名称分组,对每个产品的历史记录按时间排序,对比最新两次的价格:

price_alerts = []

# 按产品名称分组
product_groups = df.groupby('Item')

for product, group in product_groups:
    # 按日期、时间排序,确保最新记录在末尾
    sorted_records = group.sort_values(by=['Date', 'Time'])
    # 获取该产品的所有价格记录
    price_history = sorted_records['Cost'].dropna().tolist()
    
    # 至少有两条记录才需要对比
    if len(price_history) >= 2:
        latest_price = price_history[-1]
        prev_price = price_history[-2]
        
        # 价格发生变化时记录信息
        if latest_price != prev_price:
            latest_time = f"{sorted_records.iloc[-1]['Date']} {sorted_records.iloc[-1]['Time']}"
            price_alerts.append({
                '产品名称': product.title(),  # 转回正常大小写显示
                '之前价格': prev_price,
                '当前价格': latest_price,
                '变动时间': latest_time
            })

3. 实时爬取后对比的优化方案

如果是每次爬取新数据后立即对比,不需要读取全部历史记录,只需获取每个产品的最新一条价格:

# 提取每个产品的最新价格记录
latest_prices = df.sort_values(by=['Date', 'Time']).groupby('Item').last()['Cost'].to_dict()

# 假设本次爬取的数据存储在new_data列表中,格式为[{'productName': 'xxx', 'productPrice': xx}, ...]
for item in new_data:
    product_name = item['productName'].strip().lower()
    new_price = float(item['productPrice'])
    
    # 产品已有记录时对比价格
    if product_name in latest_prices:
        if new_price != latest_prices[product_name]:
            # 此处触发邮件提醒逻辑
            print(f"产品{product_name.title()}价格变动:{latest_prices[product_name]} → {new_price}")
    # 首次记录的产品无需对比,直接写入Excel
    else:
        print(f"新增产品:{product_name.title()},价格{new_price}")

关键注意点

  • 必须确保Cost列是数值类型,否则字符串对比会出错(比如"69.99"和69.99)
  • 产品名称要做标准化处理,避免因空格、大小写、标点差异导致分组错误
  • 如果使用openpyxl而非pandas,逻辑类似:遍历行按产品名称分组,手动维护每个产品的最新价格

内容的提问来源于stack exchange,提问作者vks2910

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 03:25:20