ProxyForge Download

Building a Price Intelligence System in Python: Scraping, APIs, and Proxies

Building a Price Intelligence System in Python: Scraping, APIs, and Proxies

In today’s competitive market, staying ahead often means being on top of product prices. Whether you're a developer tasked with building an internal price intelligence system or looking to automate your online shopping experience, this guide will walk you through creating a robust solution using Python. We'll cover two main approaches: scraping data from retailers and integrating structured product APIs like the Rainforest API or Oxylabs Amazon Scraper API. For non-API targets, we’ll use BeautifulSoup + requests with residential proxies for reliable access. Finally, we'll set up a normalization layer to standardize price, currency, and SKU data, store it in SQLite, and trigger alerts on significant changes.

Introduction

Price intelligence involves monitoring prices of products across various retailers and understanding trends over time. This can be achieved through web scraping (directly accessing HTML content) or API integration (using official product APIs). Each method has its pros and cons, and the choice largely depends on your budget, the volume of data you need, and the specific requirements of your project.

Scraping vs. Structured Product APIs

DIY Scraping with BeautifulSoup + Requests

Scraping involves extracting data directly from web pages using tools like BeautifulSoup and requests. This method is cost-effective but requires dealing with HTML structures and potential anti-scraping measures from retailers. Let’s walk through a basic setup.

#### Example Code for Scraping

import requests
from bs4 import BeautifulSoup
import sqlite3

def scrape_price(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'
    }
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # Example of extracting price and currency
    price_tag = soup.find('span', {'id': 'priceblock_ourprice'})
    if price_tag:
        return {
            'price': float(price_tag.text.replace('$', '')),
            'currency': 'USD'
        }
    else:
        raise ValueError("Price tag not found")

# Store data in SQLite
def store_price_data(sku, price_data):
    conn = sqlite3.connect('prices.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS prices (sku TEXT, price REAL, currency TEXT)''')
    c.execute('INSERT INTO prices VALUES (?, ?, ?)', (sku, price_data['price'], price_data['currency']))
    conn.commit()
    conn.close()

# Example usage
url = 'https://www.amazon.com/dp/B08N59YRYF'
try:
    data = scrape_price(url)
    store_price_data('B08N59YRYF', data)
except Exception as e:
    print(f"Error: {e}")

Cost: DIY scraping incurs costs for proxies. Residential proxies are generally more expensive but offer better reliability and lower chance of being blocked.

Structured Product APIs

Structured APIs like Rainforest or Oxylabs Amazon Scraper provide a more reliable and efficient way to access product data without the hassle of dealing with HTML. They are priced per request, which can be cost-effective for low volumes.

#### Example Code for API Integration (Rainforest)

import requests
import sqlite3

def fetch_price_via_api(asin):
    api_key = 'YOUR_API_KEY'
    url = f'https://api.rainforestapi.com/request?api_key={api_key}&type=product&asin={asin}'
    
    response = requests.get(url)
    data = response.json()
    
    if 'price' in data:
        return {
            'price': float(data['price']),
            'currency': 'USD'
        }
    else:
        raise ValueError("Price not found")

# Store data in SQLite
def store_price_data(sku, price_data):
    conn = sqlite3.connect('prices.db')
    c = conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS prices (sku TEXT, price REAL, currency TEXT)''')
    c.execute('INSERT INTO prices VALUES (?, ?, ?)', (sku, price_data['price'], price_data['currency']))
    conn.commit()
    conn.close()

# Example usage
asin = 'B08N59YRYF'
try:
    data = fetch_price_via_api(asin)
    store_price_data('B08N59YRYF', data)
except Exception as e:
    print(f"Error: {e}")

Cost: Rainforest API costs $0.001 per request, which can be more cost-effective for high volumes of data compared to the initial setup and maintenance costs of DIY scraping.

Normalization Layer

Normalization ensures that price data is consistent across different sources by converting prices to a common currency (e.g., USD) and standardizing SKU formats. This step is crucial for accurate comparison and alerting.

#### Example Code for Normalization

def normalize_price(price_data, target_currency='USD'):
    # Convert price to target currency if necessary
    if price_data['currency'] != target_currency:
        exchange_rate = get_exchange_rate(price_data['currency'], target_currency)
        price_data['price'] *= exchange_rate
        price_data['currency'] = target_currency
    return price_data

def get_exchange_rate(from_currency, to_currency):
    # Example: Fetching exchange rate from an API (e.g., Open Exchange Rates)
    api_key = 'YOUR_EXCHANGE_API_KEY'
    url = f'https://openexchangerates.org/api/latest.json?app_id={api_key}'
    
    response = requests.get(url)
    data = response.json()
    return data['rates'][to_currency] / data['rates'][from_currency]

# Example usage
price_data = {'price': 120, 'currency': 'EUR'}
normalized_price = normalize_price(price_data)
print(normalized_price)

Daily Diff and Alerts

To monitor price changes, set up a daily job to compare current prices with stored values. If the difference exceeds a specified threshold, send an alert via Telegram or Slack.

#### Example Code for Daily Diff and Alerts

import sqlite3
from datetime import datetime, timedelta
import telegram

def check_price_changes():
    conn = sqlite3.connect('prices.db')
    c = conn.cursor()
    
    # Fetch latest prices
    c.execute('''SELECT sku, price FROM prices WHERE timestamp > ?''', (datetime.now() - timedelta(days=1),))
    new_prices = {row[0]: row[1] for row in c.fetchall()}
    
    # Compare with stored prices
    c.execute('SELECT * FROM previous_prices')
    old_prices = {row[0]: row[1] for row in c.fetchall()}
    
    alerts = []
    for sku, new_price in new_prices.items():
        if sku in old_prices and abs(new_price - old_prices[sku]) > 5:  # Example threshold of $5
            alerts.append(f"Price change detected for SKU {sku}: {old_prices[sku]} -> {new_price}")
    
    conn.close()
    
    if alerts:
        send_alerts(alerts)

def send_alerts(messages):
    bot = telegram.Bot(token='YOUR_TELEGRAM_BOT_TOKEN')
    chat_id = 'YOUR_CHAT_ID'
    for message in messages:
        bot.send_message(chat_id=chat_id, text=message)

# Example usage
check_price_changes()

Conclusion

Building a price intelligence system involves choosing between DIY scraping and structured product APIs. Each method has its trade-offs, with APIs offering more reliability and cost-efficiency for higher volumes of data. Normalization ensures consistent pricing data, while daily diff and alerting help you stay informed about significant changes.

If you prefer not to manage proxy lists manually or need reliable rotating proxies for production use, consider services like Bright Data and SmartProxy. They offer residential proxies that reduce the risk of being blocked.

ProxyForge: If you'd rather not manage proxy lists manually, ProxyForge auto-tests and rotates proxies locally on your machine — one-off $29 unlock, no subscription: https://proxyforge.dev/#download

This guide should provide a solid foundation for building a price intelligence system in Python. Remember to always comply with retailer terms of service and consider legal implications when scraping data.

Free proxies break. ProxyForge doesn't.

The free lists above are public and often unreliable. ProxyForge auto-tests and rotates proxies on your machine, your IP — no stale lists, no shared pools, no surprises. One-off purchase, no subscription.

Download ProxyForge free →