# Monitor Competitor Prices

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

Set up automated price monitoring across competitor websites using the FourA API.

## What You'll Build

A Python script that:
1. Fetches product pages from a list of competitor URLs
2. Extracts price data from the HTML
3. Logs results to a CSV file
4. Runs on a schedule

## Prerequisites

- A FourA API key ([get one here](https://foura.ai/dashboard))
- Python 3.8+
- `requests` and `beautifulsoup4` packages

```bash
pip install requests beautifulsoup4
```

## Step 1: Define Your Targets

Create a list of product URLs to monitor:

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

## Step 2: Fetch Pages via 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}")
```

A `429` with `plan_limit_credits`, `plan_limit_bandwidth` or `plan_limit_browser_daily` in `X-FourA-Limit` won't clear by waiting a few seconds, so the function stops instead of retrying. See [Rate Limits](https://foura.ai/docs/api/rate-limits) for every limit and when it resets.

## Step 3: Extract Prices

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

## Step 4: Run and Log Results

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

## Step 5: Schedule It

Run the script hourly with cron:

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

## Tips

- **Start with the single endpoint**, switch to browser if pages use JavaScript rendering
- **Add error handling**: sites change layouts. Log failures separately.
- **Keep selectors updated**: when a competitor redesigns, update the CSS selector
- **Respect the sites**: space requests, avoid peak hours, follow robots.txt

## Next Steps

- [Choosing the Right Endpoint](https://foura.ai/docs/guides/choosing-task-type): Pick the best approach
- [Error Handling](https://foura.ai/docs/api/errors): Handle failures gracefully
- [Scrape a Dynamic Website](https://foura.ai/docs/how-to/scrape-dynamic-website): Handle JavaScript-rendered pages
