# مراقبة أسعار المنافسين

> URL: https://foura.ai/ar/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 ([احصل على واحد من هنا](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}")
```

لن يُحل رمز `429` مع `plan_limit_credits` أو `plan_limit_bandwidth` أو `plan_limit_browser_daily` في `X-FourA-Limit` بالانتظار لبضع ثوانٍ، لذا تتوقف الدالة بدلاً من إعادة المحاولة. راجع [Rate Limits](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 الخاص بك
- **احترم المواقع**: باعد بين الـ requests، وتجنب أوقات الذروة، والتزم بملف 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
