监控竞品价格

使用 FourA API 在竞争对手网站上设置自动化价格监控。

你将构建的内容

一个具备以下功能的 Python 脚本:

  1. 从竞争对手 URL 列表中抓取产品页面
  2. 从 HTML 中提取价格数据
  3. 将结果记录到 CSV 文件
  4. 按计划定时运行

前提条件

  • 一个 FourA API key(在此处获取)
  • Python 3.8+
  • requests 和 beautifulsoup4 依赖包
pip install requests beautifulsoup4

步骤 1:定义监控目标

创建要监控的产品 URL 列表:

targets = [
    {"name": "Competitor A - Widget", "url": "https://competitor-a.com/widget", "selector": ".price"},
    {"name": "Competitor B - Widget", "url": "https://competitor-b.com/products/widget", "selector": "[data-price]"},
    {"name": "Competitor C - Widget", "url": "https://competitor-c.com/item/123", "selector": ".product-price span"},
]

步骤 2:通过 FourA 获取页面

import requests
import time

SINGLE_URL = "https://eu.api.foura.ai/api/single/"
BROWSER_URL = "https://eu.api.foura.ai/api/browser/"
API_KEY = "YOUR_API_KEY"

HEADERS = {
    "X-API-Key": API_KEY,
    "Content-Type": "application/json"
}

# A wait doesn't clear these: they reset with the period (credits, traffic)
# or at midnight UTC (the daily Browser allowance).
STOP_LIMITS = {"plan_limit_credits", "plan_limit_bandwidth", "plan_limit_browser_daily"}

def fetch_page(url, use_browser=False, attempts=3):
    if use_browser:
        endpoint, field = BROWSER_URL, "body"
        payload = {"url": url, "timeout_ms": 15000}
    else:
        endpoint, field = SINGLE_URL, "data"
        payload = {"method": "GET", "url": url, "unblocker": True}
    for _ in range(attempts):
        resp = requests.post(endpoint, headers=HEADERS, json=payload)
        if resp.status_code != 429:
            return resp.json().get(field, "")
        limit = resp.headers.get("X-FourA-Limit")
        if limit in STOP_LIMITS:
            raise RuntimeError(f"Plan limit reached: {limit}")
        time.sleep(int(resp.headers.get("Retry-After", "5")))
    raise RuntimeError(f"Still rate limited after {attempts} attempts: {url}")

带有 plan_limit_credits、plan_limit_bandwidth 或 X-FourA-Limit 中的 plan_limit_browser_daily 的 429 无法通过等待几秒钟解决,因此该函数将停止而不是重试。有关各项限制及其重置时间,请参阅 Rate Limits。

Step 3: Extract Prices

from bs4 import BeautifulSoup
import re

def extract_price(html, selector):
    soup = BeautifulSoup(html, "html.parser")
    element = soup.select_one(selector)
    if not element:
        return None
    # Extract numeric price from text like "$49.99" or "49,99 EUR"
    text = element.get_text(strip=True)
    match = re.search(r'[\d,.]+', text)
    return float(match.group().replace(',', '.')) if match else None

步骤 4:运行并记录结果

import csv
from datetime import datetime

def monitor_prices():
    timestamp = datetime.now().isoformat()
    results = []

    for target in targets:
        html = fetch_page(target["url"])
        price = extract_price(html, target["selector"])
        results.append({
            "timestamp": timestamp,
            "name": target["name"],
            "url": target["url"],
            "price": price
        })
        print(f"{target['name']}: {price}")
        time.sleep(1)  # Be polite

    # Append to CSV
    with open("prices.csv", "a", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=["timestamp", "name", "url", "price"])
        if f.tell() == 0:
            writer.writeheader()
        writer.writerows(results)

if __name__ == "__main__":
    monitor_prices()

步骤 5:设置定时任务

使用 cron 每小时运行一次脚本:

crontab -e
# Add this line:
0 * * * * cd /path/to/project && python3 monitor.py >> monitor.log 2>&1

提示

  • 从单一 endpoint 开始,若页面使用 JavaScript 渲染则切换至浏览器
  • 添加错误处理:目标网站可能会更改布局。单独记录失败日志。
  • 保持选择器更新:当竞品网站重构时,及时更新 CSS 选择器
  • 遵守目标站点规范:控制 request 间隔,避开高峰期,遵循 robots.txt

后续步骤

更新于: 2026年9月23日