# 监控竞品价格

> URL: https://foura.ai/zh/docs/how-to/monitor-competitor-prices
> Updated: 2026-11-05
> Index: https://foura.ai/llms.txt

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

## 构建内容

一个具备以下功能的 Python 脚本：
1. 从竞争对手 URL 列表中抓取产品页面
2. 从 HTML 中提取价格数据
3. 将结果记录到 CSV 文件
4. 按计划定时运行

## 前提条件

- FourA API key（[在此获取](https://foura.ai/dashboard)）
- Python 3.8+
- `requests` 和 `beautifulsoup4` 包

```bash
pip install requests beautifulsoup4
```

## 步骤 1：定义目标

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

```python
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 获取页面

```python
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` 或 `plan_limit_browser_daily` 的 `429`（位于 `X-FourA-Limit` 中）无法通过等待几秒解决，因此函数会直接停止而不是重试。关于各项限制及其重置时间，请参见 [速率限制](https://foura.ai/docs/api/rate-limits)。

## 步骤 3：提取价格

```python
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[\d,.]*', text)
    if not match:
        return None
    number = match.group().rstrip(',.')
    # The last comma or dot is the decimal mark when exactly two digits follow it.
    whole, mark, cents = number.replace(',', '.').rpartition('.')
    if mark and len(cents) == 2:
        return float(whole.replace('.', '') + '.' + cents)
    return float(number.replace(',', '').replace('.', ''))
```

## 步骤 4：运行并记录结果

```python
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 每小时运行一次脚本：

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

## 提示

- **从单个 endpoint 开始**，若页面使用 JavaScript 渲染再切换到浏览器
- **添加错误处理**：网站可能会更改布局。单独记录失败日志。
- **保持选择器更新**：当竞品重新设计页面时，及时更新 CSS 选择器
- **遵守目标网站规则**：拉开 request 间隔，避开高峰时段，遵循 robots.txt

## 后续步骤

- [选择合适的 Endpoint](https://foura.ai/docs/guides/choosing-task-type)：挑选最佳方案
- [错误处理](https://foura.ai/docs/api/errors)：优雅处理失败情况
- [抓取动态网站](https://foura.ai/docs/how-to/scrape-dynamic-website)：处理 JavaScript 渲染的页面
