# Monitorowanie cen konkurencji

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

Skonfiguruj automatyczne monitorowanie cen na stronach konkurencji za pomocą API FourA.

## Co zbudujesz

Skrypt w języku Python, który:
1. Pobiera strony produktów z listy adresów URL konkurencji
2. Wyodrębnia dane o cenach z kodu HTML
3. Zapisuje wyniki w pliku CSV
4. Działa według harmonogramu

## Wymagania wstępne

- Klucz API FourA ([pobierz go tutaj](https://foura.ai/dashboard))
- Python 3.8+
- Pakiety `requests` oraz `beautifulsoup4`

```bash
pip install requests beautifulsoup4
```

## Krok 1: Zdefiniuj cele

Utwórz listę adresów URL produktów do monitorowania:

```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"},
]
```

## Krok 2: Pobieranie stron przez 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}")
```

Błąd `429` z `plan_limit_credits`, `plan_limit_bandwidth` lub `plan_limit_browser_daily` w `X-FourA-Limit` nie ustąpi po odczekaniu kilku sekund, więc funkcja przerywa działanie zamiast ponawiać próbę. Sprawdź [Rate Limits](https://foura.ai/docs/api/rate-limits), aby poznać wszystkie limity oraz czas ich resetowania.

## Krok 3: Wyodrębnianie cen

```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('.', ''))
```

## Krok 4: Uruchomienie i rejestrowanie wyników

```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()
```

## Krok 5: Zaplanuj zadanie

Uruchamiaj skrypt co godzinę za pomocą cron:

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

## Wskazówki

- **Zacznij od pojedynczego endpointu**, przełącz się na przeglądarkę, jeśli strony używają renderowania JavaScript
- **Dodaj obsługę błędów**: strony zmieniają układy. Loguj niepowodzenia osobno.
- **Aktualizuj selektory na bieżąco**: gdy konkurencja zmienia wygląd strony, zaktualizuj selektor CSS
- **Szanuj serwisy**: rozkładaj requesty w czasie, unikaj godzin szczytu, przestrzegaj robots.txt

## Kolejne kroki

- [Wybór odpowiedniego endpointu](https://foura.ai/docs/guides/choosing-task-type): Wybierz najlepsze podejście
- [Obsługa błędów](https://foura.ai/docs/api/errors): Bezproblemowo obsługuj błędy
- [Scrapowanie dynamicznej strony internetowej](https://foura.ai/docs/how-to/scrape-dynamic-website): Obsługuj strony renderowane w JavaScript
