A-A+

DMIT 指定商品库存监控脚本(Playwright 版)

2026年04月17日 18:35 学习笔记 暂无评论 共2074字 (阅读4 views次)

【注意:此文章为博主原创文章!转载需注意,请带原文链接,至少也要是txt格式!】

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/usr/bin/env python3
"""
DMIT 商品库存监控脚本(Playwright 版)
每 360 秒检测一次,仅有货时发通知
"""
 
import time
import subprocess
import sys
from datetime import datetime
 
# ── 配置 ──────────────────────────────────────────
URL = "https://woj.app/url.php?id=186" ##这里是参考https://woj.app/9698.html 这里的VPS产品进行购买
CHECK_INTERVAL = 360  # 检查间隔(秒)
 
OUT_OF_STOCK_KEYWORDS = [
    "out of stock",
    "currently unavailable",
    "no longer available",
    "out-of-stock",
    "product is out of stock",
    "product is not available",
]
# ──────────────────────────────────────────────────
 
 
def notify(title: str, message: str, sound: str = "Glass") -> None:
    script = f'display notification "{message}" with title "{title}" sound name "{sound}"'
    subprocess.run(["osascript", "-e", script])
 
 
def check_stock() -> tuple[bool, str]:
    from playwright.sync_api import sync_playwright
 
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context(
            user_agent=(
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
                "AppleWebKit/537.36 (KHTML, like Gecko) "
                "Chrome/124.0.0.0 Safari/537.36"
            )
        )
        page = context.new_page()
        try:
            resp = page.goto(URL, wait_until="domcontentloaded", timeout=30000)
            if resp and resp.status == 404:
                return False, "页面不存在(404)"
 
            page.wait_for_timeout(3000)
            html = page.content().lower()
 
            for keyword in OUT_OF_STOCK_KEYWORDS:
                if keyword in html:
                    return False, "缺货"
 
            if (
                page.query_selector('input[name="a"][value="add"]') or
                page.query_selector(".order-button") or
                "configoptions" in html or
                "orderbutton" in html or
                "add to cart" in html
            ):
                return True, "有货"
 
            return False, "状态未知"
 
        except Exception as e:
            return False, f"异常: {e}"
        finally:
            browser.close()
 
 
def main():
    try:
        import playwright  # noqa
    except ImportError:
        print("❌ 未安装 playwright,请先执行:")
        print("   pip3 install playwright")
        print("   python3 -m playwright install chromium")
        sys.exit(1)
 
    print(f" 开始监控: {URL}")
    print(f"⏱  检查间隔: {CHECK_INTERVAL} 秒")
    print("按 Ctrl+C 停止\n")
 
    while True:
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        in_stock, status = check_stock()
 
        if in_stock:
            print(f"[{now}] ✅ {status}")
            notify(" DMIT 有货啦!", "pid=186 现在可以购买!快去下单!", sound="Glass")
        else:
            # 缺货/异常只打日志,不发通知
            print(f"[{now}] ❌ {status}")
 
        try:
            time.sleep(CHECK_INTERVAL)
        except KeyboardInterrupt:
            print("\n已停止监控")
            sys.exit(0)
 
 
if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\n已停止监控")

布施恩德可便相知重

微信扫一扫打赏

支付宝扫一扫打赏

×

给我留言