之前一个朋友让我用Python写一个实时监控医药商城网站价格的程序。接下来,我得考虑技术实现。Python有很多库适合网页抓取,比如requests和BeautifulSoup。但如果网站是动态加载的,可能需要用Selenium或者Playwright。另外,处理反爬机制也是问题,可能需要设置User-Agent,使用代理,或者处理验证码。
然后,存储数据的话,用户可能需要记录历史价格,方便后续分析。用CSV文件简单,但如果数据量大,可能要考虑数据库,比如SQLite或MySQL。不过用户可能刚开始只需要简单存储,所以先实现CSV。
定时监控的话,可以用time.sleep,但更可靠的方式可能是用APScheduler或者cron job。不过用户可能希望程序长时间运行,所以简单的循环加延迟可能更直接。
通知功能,用户可能想要邮件或者短信提醒。这里需要集成SMTP或者第三方API,比如Twilio。但考虑到复杂度,先实现邮件通知,用户需要提供邮箱和密码,不过要注意安全性,可能建议使用应用专用密码。
然后,解析网页内容部分,需要根据目标网站的结构来写XPath或CSS选择器。但不同网站结构不同,可能需要用户自定义,或者程序需要灵活配置。这里可能需要用户自己修改选择器,或者在代码中注释说明。
以下是一个简单的医药商城网站价格监控程序的Python示例代码,包含基本功能和注意事项:
import requests
from bs4 import BeautifulSoup
import time
import smtplib
from email.mime.text import MIMEText
import csv
from datetime import datetime
# 配置参数
WEBSITES = {
'示例医药网': 'https://www.example-drugstore.com/product/123'
}
PRICE_CHECK_INTERVAL = 3600 # 检查间隔(秒)
TARGET_PRICE = 50.00 # 目标提醒价格
EMAIL_SETTINGS = {
'sender': 'your_email@example.com',
'receiver': 'your_email@example.com',
'password': 'your_email_password',
'smtp_server': 'smtp.example.com'
}
# 伪装浏览器头
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
def get_price(url):
try:
response = requests.get(url, headers=HEADERS, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# 需要根据实际网站结构调整选择器
price_element = soup.select_one('.product-price')
if price_element:
price_str = price_element.text.strip().replace('¥', '').replace(',', '')
return float(price_str)
return None
except Exception as e:
print(f"获取价格失败: {str(e)}")
return None
def send_alert(subject, message):
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = EMAIL_SETTINGS['sender']
msg['To'] = EMAIL_SETTINGS['receiver']
try:
server = smtplib.SMTP_SSL(EMAIL_SETTINGS['smtp_server'], 465)
server.login(EMAIL_SETTINGS['sender'], EMAIL_SETTINGS['password'])
server.sendmail(EMAIL_SETTINGS['sender'],
EMAIL_SETTINGS['receiver'],
msg.as_string())
server.quit()
print("邮件提醒已发送")
except Exception as e:
print(f"发送邮件失败: {str(e)}")
def save_to_csv(data):
with open('price_history.csv', 'a', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(data)
def monitor():
while True:
print(f"\n{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} 开始价格检查...")
for site_name, url in WEBSITES.items():
current_price = get_price(url)
if current_price is None:
continue
print(f"{site_name} 当前价格: ¥{current_price:.2f}")
# 保存历史记录
save_to_csv([
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
site_name,
current_price
])
# 价格提醒
if current_price <= TARGET_PRICE:
subject = f"[价格提醒] {site_name} 价格降至 ¥{current_price:.2f}"
message = f"商品链接:{url}\n当前价格:¥{current_price:.2f}"
send_alert(subject, message)
time.sleep(PRICE_CHECK_INTERVAL)
if __name__ == '__main__':
# 初始化CSV文件
with open('price_history.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['时间', '网站名称', '价格'])
print("启动价格监控程序...")
monitor()
使用说明和注意事项:
-
需要根据目标网站实际结构修改:
- 价格选择器(
.product-price
) - 可能需要处理登录、验证码等反爬机制
- 遵守目标网站的robots.txt协议
- 价格选择器(
-
需配置的参数:
- WEBSITES字典:添加需要监控的网址
- 邮件服务器设置(建议使用专门的监控邮箱)
- 价格检查间隔和目标价格
-
扩展建议:
# 可添加的功能 - 使用代理IP池(应对反爬) - 添加数据库存储(替代CSV) - 多页商品监控 - 价格变化趋势分析 - 网站API直接调用(如果有提供)
-
重要法律声明:
- 使用前请确保遵守目标网站的服务条款
- 控制请求频率避免对服务器造成压力
- 本代码仅用于学习目的,请勿用于商业用途
-
运行环境要求:
pip install requests beautifulsoup4
请根据实际需求调整代码,并确保遵守相关法律法规和网站的使用条款。对于复杂的电商网站,建议使用官方API(如果有提供)来获取价格信息。