HOOOS

Python商品价格监控:低于预设值自动邮件提醒,手把手教你实现

0 6 降价提醒小助手 Python商品价格监控邮件提醒
Apple

想第一时间知道心仪商品降价了吗?用Python写个脚本,让它帮你盯着!当商品价格低于你设定的值,它就自动发邮件通知你,再也不怕错过好价啦!

本文将一步步教你如何用Python实现这个功能,以京东为例,其他电商平台思路类似,但可能需要调整代码。

1. 准备工作

  • 安装必要的库:

    pip install requests beautifulsoup4 yagmail
    
    • requests: 用于发送HTTP请求,获取网页内容。
    • beautifulsoup4: 用于解析HTML网页,提取商品价格。
    • yagmail: 用于发送邮件。
  • 注册邮箱并开启SMTP服务:

    你需要一个邮箱来发送提醒邮件。以QQ邮箱为例,你需要登录网页版QQ邮箱,进入“设置 -> 账户”,开启POP3/SMTP服务,并获取授权码(用于代替密码)。

2. 代码实现

2.1 获取商品价格

首先,我们需要找到目标商品的URL。在京东商品页面,打开开发者工具(F12),在“Network”选项卡中,刷新页面,找到包含商品价格的请求。通常,价格信息会包含在一个JSON文件中。分析请求URL和返回数据,找到价格所在的字段。

以下代码以模拟用户访问京东商品页面为例,你需要替换url为你要监控的商品链接。

import requests
from bs4 import BeautifulSoup

# 替换成你要监控的商品链接
url = 'https://item.jd.com/xxxxxxxxx.html' 

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}

def get_price(url):
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()  # 检查请求是否成功
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 京东商品价格通常在 class_='price' 的 i 标签中
        price_element = soup.find('i', class_='price')
        if price_element:
            price = float(price_element.text)
            return price
        else:
            print("未找到价格元素")
            return None
    except requests.exceptions.RequestException as e:
        print(f"请求出错: {e}")
        return None
    except Exception as e:
        print(f"解析出错: {e}")
        return None

price = get_price(url)
if price:
    print(f"当前价格: {price}")
else:
    print("无法获取价格")

代码解释:

  • requests.get(url, headers=headers): 发送GET请求,获取网页内容。headers用于模拟浏览器访问,防止被网站识别为爬虫。
  • response.raise_for_status(): 检查请求是否成功,如果状态码不是200,会抛出异常。
  • BeautifulSoup(response.text, 'html.parser'): 使用BeautifulSoup解析HTML网页。
  • soup.find('i', class_='price'): 查找class为pricei标签,该标签通常包含商品价格。
  • float(price_element.text): 将价格字符串转换为浮点数。

注意事项:

  • 不同的电商平台,HTML结构可能不同,你需要根据实际情况调整代码。
  • 有些网站会采用反爬虫机制,需要设置合适的User-Agent,甚至使用代理IP。

2.2 发送邮件

使用yagmail库发送邮件。你需要替换以下代码中的邮箱账号、授权码、收件人邮箱。

import yagmail

# 替换成你的邮箱账号、授权码、收件人邮箱
sender_email = 'your_email@example.com'
sender_password = 'your_authorization_code'
receiver_email = 'receiver_email@example.com'


def send_email(subject, content):
    try:
        yag = yagmail.SMTP(user=sender_email, password=sender_password, host='smtp.qq.com', port=465, smtp_ssl=True) # QQ邮箱
        #yag = yagmail.SMTP(user=sender_email, password=sender_password) # 其他邮箱
        yag.send(receiver_email, subject, content)
        print("邮件发送成功!")
    except Exception as e:
        print(f"邮件发送失败: {e}")

# 示例:发送邮件
# send_email('价格提醒', '商品价格已低于预设值!')

代码解释:

  • yagmail.SMTP(user=sender_email, password=sender_password, host='smtp.qq.com', port=465, smtp_ssl=True): 连接SMTP服务器。你需要根据你的邮箱类型,修改hostport参数。QQ邮箱需要开启SSL加密,端口为465。
  • yag.send(receiver_email, subject, content): 发送邮件。receiver_email为收件人邮箱,subject为邮件主题,content为邮件内容。

2.3 整合代码

将获取商品价格和发送邮件的代码整合在一起,设置价格阈值,当商品价格低于阈值时,发送邮件通知。

import requests
from bs4 import BeautifulSoup
import yagmail
import time

# 替换成你要监控的商品链接
url = 'https://item.jd.com/xxxxxxxxx.html'
# 替换成你的邮箱账号、授权码、收件人邮箱
sender_email = 'your_email@example.com'
sender_password = 'your_authorization_code'
receiver_email = 'receiver_email@example.com'

# 设置价格阈值
threshold_price = 100.0

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}

def get_price(url):
    try:
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, 'html.parser')
        price_element = soup.find('i', class_='price')
        if price_element:
            price = float(price_element.text)
            return price
        else:
            print("未找到价格元素")
            return None
    except requests.exceptions.RequestException as e:
        print(f"请求出错: {e}")
        return None
    except Exception as e:
        print(f"解析出错: {e}")
        return None

def send_email(subject, content):
    try:
        yag = yagmail.SMTP(user=sender_email, password=sender_password, host='smtp.qq.com', port=465, smtp_ssl=True)
        yag.send(receiver_email, subject, content)
        print("邮件发送成功!")
    except Exception as e:
        print(f"邮件发送失败: {e}")

while True:
    price = get_price(url)
    if price:
        print(f"当前价格: {price}")
        if price < threshold_price:
            subject = '价格提醒!'
            content = f'商品 {url} 价格已降至 {price},低于预设值 {threshold_price}!快去抢购吧!'
            send_email(subject, content)
            break  # 发送邮件后停止监控,可以注释掉这行,让脚本持续监控
        else:
            print(f"价格未低于预设值 {threshold_price}")
    else:
        print("无法获取价格")

    time.sleep(3600)  # 每隔一小时监控一次,可以根据需要调整

代码解释:

  • threshold_price: 设置价格阈值,当商品价格低于该值时,发送邮件。
  • while True:: 循环监控商品价格。
  • time.sleep(3600): 每隔一小时监控一次。你可以根据需要调整监控频率。
  • break: 发送邮件后停止监控。如果你想让脚本持续监控,可以注释掉这行。

3. 运行脚本

将代码保存为.py文件,例如price_monitor.py,然后在命令行中运行:

python price_monitor.py

4. 总结

通过以上步骤,你就可以用Python实现一个简单的商品价格监控脚本。当然,这只是一个基础版本,你可以根据自己的需求进行扩展,例如:

  • 添加多个商品监控。
  • 使用数据库存储商品价格历史记录。
  • 添加图形界面,方便用户设置参数。
  • 使用更高级的反爬虫技术,应对更复杂的网站。

希望本文能帮助你实现商品价格监控,祝你购物愉快!

点评评价

captcha
健康