一、实现功能
在CHATGPT的帮助下,用python写了一个简单的价格监控程序。
实现了如下功能:
1.获取现在价格
2.当低于某个价格时提醒
3.邮件提醒
4.每天发邮件证明程序仍在运行
二、代码如下
import requests
from bs4 import BeautifulSoup
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import time
from datetime import datetime, timedelta
import pytz
# 设置邮箱信息
my_email = "[email protected]"
my_password = "123456"
recipient_email = "[email protected]"
# 商品链接和监控价格列表,target_price后面填写你意向的价格
products = [
{"url": "https://www.usa.canon.com/shop/p/refurbished-rf50mm-f1-8-stm", "target_price": 100, "reached_target": False, "last_price": None},
{"url": "https://www.usa.canon.com/shop/p/refurbished-eos-r8?color=Black&type=Refurbished", "target_price": 600, "reached_target": False, "last_price": None}
]
def get_price(url):
"""获取指定URL的商品价格"""
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.content, "html.parser")
if "canon.com" in url:
price_tag = soup.find("span", {"class": "price"})
if price_tag:
price_str = price_tag.text.strip().replace("$", "").replace(",", "")
return float(price_str)
else:
raise ValueError("价格标签未找到")
else:
raise ValueError("不支持的URL格式")
except requests.RequestException as e:
print(f"获取 {url} 价格时出错: 网络问题 - {e}")
except Exception as e:
print(f"获取 {url} 价格时出错: {e}")
return None
def send_email(subject, message):
"""发送带有指定主题和消息的电子邮件通知"""
try:
msg = MIMEText(message, "plain", "utf-8")
msg["Subject"] = Header(subject, "utf-8")
msg["From"] = my_email
msg["To"] = recipient_email
server = smtplib.SMTP_SSL("smtp.exmail.qq.com", 465)
server.login(my_email, my_password)
server.sendmail(my_email, recipient_email, msg.as_string())
server.quit()
print("邮件发送成功。")
except Exception as e:
print(f"发送邮件时出错: {e}")
def main():
"""主函数,用于监控商品价格并发送通知"""
# 设置时区为北京时间
tz = pytz.timezone('Asia/Shanghai')
while True:
now = datetime.now(tz)
current_time = now.strftime("%H:%M:%S")
# 每天早上8点发送确认邮件
if current_time == "08:00:00":
subject = "程序运行确认"
message = "您的监控程序仍在运行中。"
send_email(subject, message)
print("开始监控,当前时间:", now)
for p in products:
current_price = get_price(p["url"])
if current_price is not None:
print(f"商品 {p['url']} 当前价格为 ${current_price}")
if current_price <= p["target_price"]:
if not p["reached_target"] or (p["last_price"] is not None and current_price > p["last_price"]):
subject = "商品价格到目标值!"
message = f"商品 {p['url']} 当前价格为 ${current_price},已达到你设置的目标价格 ${p['target_price']}。"
send_email(subject, message)
print(f"商品 {p['url']} 当前价格为 ${current_price}")
p["reached_target"] = True
else:
p["reached_target"] = False # 价格上涨后恢复监控状态
p["last_price"] = current_price
# 打印下一次检查的时间并等待1小时
next_check_time = now + timedelta(hours=1)
print(f"本次监控结束,下一次监控时间:{next_check_time} (间隔时间1小时)")
time.sleep(3600)
if __name__ == "__main__":
main()
三、使用以下代码在vps后台运行
nohup python3 your_script.py > script.log 2>&1 &
四、查看后台进程
ps aux | grep your_script.py