0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【自動化】10分で作る複数ECサイト競合価格監視&Slack値下げ通知パイプライン(セレクター不要・Python)

0
Posted at

EC事業や物販において、競合他社の価格変動をデイリーで把握することは売上・利益率に直結します。
しかし、自作のスクレイピングで複数ECサイトの価格を監視しようとすると、以下の課題に直面します:

  • サイトごとに異なるHTML構造とCSSセレクターの記述
  • 「税込 / 税抜」「セール価格 / 通常価格」など日本特有の表記揺れ
  • サイトのデザイン改修によるセレクター破損と定期的なメンテ工数

本記事では、LLMを活用したWeb抽出API「Scraping AI」を用いて、CSSセレクターを一切書かずに複数サイトの価格監視・Slack値下げ通知アラートをPythonで構築する方法を解説します。

全体構成

  1. データ抽出: scraping-ai Python SDKを用いて商品名・数値価格・税込判定を取得
  2. 履歴保存: ローカルのSQLiteデータベースに価格履歴を蓄積
  3. Slack通知: 設定した閾値以上の値下げがあればSlack Webhookに自動通知

実装コード(price_monitor_slack.py

pip install scraping-ai requests
import sqlite3
import requests
from datetime import datetime
from scraping_ai import ScrapingAIClient

# 設定
SCRAPING_AI_KEY = "YOUR_API_KEY"
SLACK_WEBHOOK_URL = "https://hooks.slack.com/services/YOUR/WEBHOOK/URL"

client = ScrapingAIClient(api_key=SCRAPING_AI_KEY)

# 1. SQLiteデータベースの初期化
conn = sqlite3.connect('competitor_prices.db')
conn.execute("""
    CREATE TABLE IF NOT EXISTS prices (
        product_name TEXT,
        price REAL,
        currency TEXT,
        tax_included BOOLEAN,
        url TEXT,
        checked_at DATETIME
    )
""")

def send_slack_alert(message: str):
    """Slack Webhookにアラートを送信"""
    requests.post(SLACK_WEBHOOK_URL, json={"text": message})

def check_and_alert_price(url: str):
    """URLから価格を抽出し、過去データと比較して値下げを検知する"""
    
    # 税込・税抜や通貨単位も含めて自然言語でスキーマ定義
    result = client.extract(
        url=url,
        schema={
            "product_name": "string",
            "price": "number",
            "currency": "string",
            "tax_included": "boolean",
            "in_stock": "boolean"
        }
    )
    
    for item in result.results:
        data = item['data']
        name = data.get('product_name')
        current_price = float(data.get('price', 0))
        currency = data.get('currency', 'JPY')
        
        # 過去の最新価格を取得
        cursor = conn.execute(
            "SELECT price FROM prices WHERE product_name = ? ORDER BY checked_at DESC LIMIT 1",
            (name,)
        )
        last_record = cursor.fetchone()
        
        if last_record:
            last_price = last_record[0]
            if current_price < last_price:
                drop_pct = ((last_price - current_price) / last_price) * 100
                alert_msg = f"🚨【値下げ検知】{name}\n旧価格: {last_price:,.0f} {currency} ➔ 新価格: {current_price:,.0f} {currency} ({drop_pct:.1f}% OFF)\n🔗 {url}"
                print(alert_msg)
                send_slack_alert(alert_msg)
            else:
                print(f"ℹ️ 変動なし: {name} ({current_price:,.0f} {currency})")
        
        # 今回の価格を保存
        conn.execute(
            "INSERT INTO prices VALUES (?, ?, ?, ?, ?, ?)",
            (name, current_price, currency, data.get('tax_included', True), url, datetime.now())
        )
    
    conn.commit()

if __name__ == "__main__":
    check_and_alert_price("https://example-shop.jp/products/headphones")

運用コスト試算(月間シミュレーション)

3サイトにわたり計50商品を毎日自動監視する場合:

  • 1日の想定消費トークン: 約36トークン
  • Growthプラン($30 / 5,000トークン)利用時: 月額 約$6.60(約990円)
  • セレクター改修に伴うエンジニア保守工数: 0時間

制約事項

  • SNS(XやInstagram)の価格投稿スクレイピングは規約上非対応です。
  • 極めて厳格なアンチボット防御(Cloudflare Turnstile等)に対する自動ステルス回避率は約85%です。

無料で試す(200トークン付与)

運営企業・チームについて

Scraping AIは、株式会社SMSデータテックのAIベンチャー子会社であるindigodata株式会社が開発・運営しています。国内500件以上の受託データ収集実績を持つ「PigData」の知見をベースに、開発者向けセルフサーブ型LLMスクレイピングAPIを提供しています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?