如何修改Python代码检测40码UGG鞋库存并触发Discord通知?
问题:监控Courir网站UGG Tasman 40码库存并推送Discord消息
我想开发一个机器人,当Courir网站上的UGG Tasman鞋40码补货时,自动发送Discord消息。我尝试用以下代码定位库存状态元素,但不知道怎么修改来找到40码的特定库存状态:
stock_element = soup.find('li', {'class': 'unselectable'})
我不清楚如何修改这段代码来判断40码是否有库存,以下是我写的完整代码:
import discord from bs4 import BeautifulSoup import requests import aiohttp import asyncio webhook_url = 'DISCORD API' async def send_webhook_message(content): async with aiohttp.ClientSession() as session: async with session.post(webhook_url, json={"content": content}) as response: if response.status == 204: print("Discord message sent successfully.") else: print(f"Error sending Discord message. Status code: {response.status}") async def check_stock(url, size): try: response = requests.get(url) response.raise_for_status() soup = BeautifulSoup(response.text, 'html.parser') stock_element = soup.find('li', {'class': 'unselectable'}) # Check if the stock_element is found and is not disabled return stock_element is not None and 'Size Variations' not in stock_element.attrs except requests.RequestException as e: print(f"Error making request to the website: {e}") return False product_data = [ {'url': 'https://www.courir.com/fr/p/ugg-tasman-1499533.html', 'size': 'tasman'}, ] async def main(): previous_stock_status = {} # Dictionary to store previous stock status for each product while True: result_message = "" for product_info in product_data: url = product_info['url'] size = product_info['size'] current_stock_status = await check_stock(url, size) # Check if the product was out of stock in the previous check and is now in stock if not previous_stock_status.get(url, {}).get(size, False) and current_stock_status: result_message += f"({size}) is now in stock\n" previous_stock_status.setdefault(url, {})[size] = current_stock_status # Check if the result message is not equal to the specific message you want to avoid if result_message.strip() != "(NAVY S) is now in stock\n(NAVY M) is now in stock\n(NAVY L) is now in stock!\n(BEIGE S) is now in stock!\n(BEIGE M) is now in stock!\n(BEIGE L) is now in stock!": # Print the result message print(result_message) # Send Discord message only if there are updates if result_message: await send_webhook_message(result_message) print("Sent Discord message.") # Sleep for a certain interval (e.g., 10 minutes) before checking again print("10 min before next check") await asyncio.sleep(200) # sleep for 10 minutes # Run the main function asynchronously asyncio.run(main())
解决方案:精准定位40码库存元素
1. 页面结构分析
通过浏览器开发者工具(F12)查看目标页面的HTML结构:
- 尺码选项通常包裹在
<li>标签中,每个尺码对应独立元素,包含尺码数字(如"40")和库存状态标识(无货时会带disabled类或aria-disabled="true"属性)。 - 你需要先确认页面中尺码元素的实际class(比如可能是
size-item或product-size,需根据页面实际情况调整)。
2. 修改check_stock函数
替换原有的模糊定位逻辑,精准匹配40码元素并判断库存状态:
async def check_stock(url, target_size): try: # 替换同步requests为异步aiohttp,避免阻塞异步循环 async with aiohttp.ClientSession() as session: # 添加请求头模拟浏览器,规避反爬 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36' } async with session.get(url, headers=headers) as response: response.raise_for_status() html = await response.text() soup = BeautifulSoup(html, 'html.parser') # 找到所有尺码选项的li元素,替换为页面实际的class size_options = soup.find_all('li', class_='product-size') for option in size_options: # 提取尺码文本,处理可能的格式(如"40 EU") size_text = option.get_text(strip=True) if target_size in size_text: # 判断是否有库存:无货元素会带disabled类或aria-disabled属性 if 'disabled' not in option.get('class', []) and option.get('aria-disabled') != 'true': return True return False # 未找到目标尺码时返回False print(f"未找到尺码 {target_size}") return False except aiohttp.ClientError as e: print(f"请求网站出错: {e}") return False
3. 调整主逻辑与配置
修正product_data和消息生成逻辑,确保只监控40码:
product_data = [ {'url': 'https://www.courir.com/fr/p/ugg-tasman-1499533.html', 'size': '40'}, ] async def main(): previous_stock_status = {} while True: result_message = "" for product_info in product_data: url = product_info['url'] target_size = product_info['size'] current_stock_status = await check_stock(url, target_size) # 仅当库存从无变有时生成通知 if not previous_stock_status.get(url, {}).get(target_size, False) and current_stock_status: result_message += f"UGG Tasman 尺码{target_size}补货了!\n商品链接:{url}\n" previous_stock_status.setdefault(url, {})[target_size] = current_stock_status # 有更新时发送消息 if result_message: print(result_message) await send_webhook_message(result_message) print("已发送Discord消息") print("10分钟后再次检查") await asyncio.sleep(600) # 修正为10分钟(600秒)
4. 关键注意事项
- 页面class可能会随网站更新变化,需定期验证尺码元素的定位规则。
- 若网站有反爬机制,可适当延长检查间隔,或添加代理IP池规避限制。
内容的提问来源于stack exchange,提问作者Marius Overgaard
相关产品推荐
相关产品推荐

