用python写一个库存监控,有货TG提醒
闲来已有多时未曾记录,趁着这几天绿云11周年活动,参看GPT摸索出了这个python脚本
- debian12系统首先安装依赖并进入虚拟
apt install -y python3-pip python3.11-venv
python3 -m venv myenv
source myenv/bin/activate
pip3 install requests beautifulsoup4 python-telegram-bot
- 在虚拟中创建文件并运行python test.py执行库存监控
import requests
from bs4 import BeautifulSoup
import time
import telegram
import asyncio
# Telegram Bot Configuration 自行填入TG信息
TELEGRAM_TOKEN = 'XXXXXXXXXXXX'
TELEGRAM_CHAT_ID = 'XXXXXX'
# URL to Monitor 监测的网址
URL = 'https://greencloudvps.com/billing/store/11th-birthday-sale/1111-hk'
# Headers to Mimic a Real Browser
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36'
}
# Initial Status of Stock 监测的关键字不区分大小写
INITIAL_STATUS = "Out of Stock"
# Variable to Track Current Stock Status
current_status = INITIAL_STATUS
# Function to Check Stock Status
def check_stock():
try:
response = requests.get(URL, headers=HEADERS)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'html.parser')
# Find the stock status, ignoring case and whitespace
if INITIAL_STATUS.lower() not in soup.get_text(strip=True).lower():
return "In Stock"
else:
return "Out of Stock"
except Exception as e:
print(f"An error occurred: {e}")
return current_status
# Function to Send Telegram Notification
async def send_telegram_notification(message):
bot = telegram.Bot(token=TELEGRAM_TOKEN)
try:
await bot.send_message(chat_id=TELEGRAM_CHAT_ID, text=message)
except telegram.error.BadRequest as e:
print(f"Failed to send message: {e}. Please check if the TELEGRAM_CHAT_ID is correct.")
# Monitoring Loop
def monitor():
global current_status
while True:
new_status = check_stock()
if new_status != current_status:
current_status = new_status
if current_status == "In Stock":
asyncio.run(send_telegram_notification("in stock! Check it now: " + URL))
elif current_status == "Out of Stock":
asyncio.run(send_telegram_notification("out of stock again."))
time.sleep(30) # Check every 30 seconds 这里改监测秒数
if __name__ == "__main__":
monitor()
- 运行python后可以执行命令退出虚拟系统
deactivate
可以更改代码中的监控页面以及关键字进行更多监控