You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python补货通知脚本开发:库存对比实现与EOL报错解决咨询

解决商品补货检测脚本的问题与优化方案

Hey there! Let's fix those issues with your stock checker script step by step, plus I'll share a more robust approach to make this work reliably.

问题1:变量比较失败的原因

你的stock是BeautifulSoup返回的Tag对象,而stock_history是一个普通字符串——直接用==比较这两种不同类型的内容肯定不会相等。你要么把stock转换成字符串形式,要么更高效地提取关键状态标识(比如按钮文本、禁用属性)来对比,完全没必要存整个HTML块。

问题2:EOL错误的原因

这个错误是因为你的stock_history字符串里包含未转义的引号,且长字符串换行时没有正确处理。硬编码完整HTML片段本身就是个坏主意:不仅容易触发语法错误,后续页面结构微调时还会直接失效。


优化后的实现方案

这里给你一个更靠谱的版本:我们只提取补货状态的核心信息,用文件存储历史状态(比硬编码灵活太多),同时修复所有语法和逻辑问题:

import requests
from datetime import datetime
from bs4 import BeautifulSoup

def get_current_stock_status():
    # 抓取目标页面并处理请求异常
    url = 'https://shop.bitmain.com/antminer_s9_asic_bitcoin_miner.htm'
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
    except requests.exceptions.RequestException as e:
        return f"Request failed: {str(e)}"
    
    # 解析页面(注意这里用正确的解析器参数)
    soup = BeautifulSoup(response.content, 'html.parser')
    
    # 定位购买按钮,提取关键状态
    buy_button = soup.find("a", class_="btn-buy-now")
    if not buy_button:
        return "Cannot find stock status element"
    
    # 提取按钮文本和禁用状态作为判断依据
    button_text = buy_button.get_text(strip=True)
    is_disabled = 'cursor:not-allowed' in buy_button.get('style', '')
    return f"Status: {button_text} | Disabled: {is_disabled}"

def load_history_status():
    # 从本地文件读取历史状态,文件不存在则返回空
    try:
        with open('stock_history.txt', 'r', encoding='utf-8') as f:
            return f.read().strip()
    except FileNotFoundError:
        return ""

def save_history_status(status):
    # 将当前状态写入文件,更新历史记录
    with open('stock_history.txt', 'w', encoding='utf-8') as f:
        f.write(status)

if __name__ == "__main__":
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    current_status = get_current_stock_status()
    history_status = load_history_status()
    
    print(f"[{current_time}] Current status: {current_status}")
    
    if current_status == history_status:
        print("No change - stock status remains the same")
    else:
        print("ALERT: Stock status changed! Check the website immediately!")
        # 这里可以扩展通知逻辑:比如发邮件、推送消息到手机等
        save_history_status(current_status)

优化亮点

  • 用函数拆分逻辑,代码更易读、易维护
  • 不存储完整HTML,只提取核心状态标识,避免字符串转义和页面小改动导致的失效
  • 用本地文件存储历史状态,无需硬编码,每次运行自动读取/更新
  • 加入请求异常捕获,避免页面访问失败导致脚本崩溃
  • 修复了原代码中if语句缺冒号、BeautifulSoup解析器参数错误的语法问题

内容的提问来源于stack exchange,提问作者Twiggy Garcia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:11:40