Introduction

In this practical guide, you will set up an automatic price monitoring system for Wildberries and Ozon using Python, mobile proxies, and Google Sheets. We will walk step by step from a clean slate to a fully functional dashboard with dynamic graphs, daily scheduled launches, and Telegram notifications for significant changes. No programming skills required. Each step is described in simple language and accompanied by checks.

By the end, you will have: 1) A Python script that collects prices, discounts, ratings, number of reviews, and stock availability from Wildberries, and pricing, Ozon Card price, rating, and category position from Ozon. 2) Mobile proxy integration to minimize blocks and rotate IPs before batches of requests. 3) Automatic data logging into Google Sheets with clear dynamic graphs. 4) Scheduled auto-start via cron on Linux or Task Scheduler on Windows. 5) Notifications in Telegram when the price changes by more than a specified percentage. 6) A set of practical tips for reliable operation and bypassing anti-bot protections without aggressive methods.

This guide is for entrepreneurs, analysts, e-commerce specialists, and beginner developers who need reliable price monitoring and metrics from marketplaces. Skill level: for beginners with straightforward steps and a few advanced segments to expand capabilities. If you can copy commands and carefully follow instructions, you’ll succeed.

What to know beforehand: basic computer skills, software installation, ability to copy text and save files. No programming required, but attention to detail is essential. Time required: 3 to 6 hours, depending on experience and speed in setting up service accounts and schedule launches.

Preparation

To ensure everything works smoothly, prepare your tools and access in advance. In this section, you will find out what to install, which accounts to create, and how to avoid common issues due to insufficient permissions or version incompatibilities.

Necessary Tools and Access

  • A computer with Windows, macOS, or Linux with internet access.
  • A Google account to use Google Sheets and Google Cloud.
  • Access to mobile proxies from mobileproxy.space (any suitable subscription that allows IP rotation management via API).
  • Python 3.11 or newer.
  • A text editor (like Notepad, VS Code, or any preferred one).

System Requirements

  • Operating system: Windows 10/11, macOS 12+, Ubuntu 20.04+ or a similar modern Linux system.
  • Free disk space: at least 500 MB.
  • Stable internet with the ability to make external HTTP/HTTPS requests.

What to Install

  • Python 3.11+: Python interpreter.
  • Python Libraries: requests, beautifulsoup4, gspread, oauth2client, schedule.
  • Optionally for convenience: virtual environment venv.

Creating Backups

The project will contain files with the configuration and Google service account credentials. Store them in a separate folder and make a backup of the credentials file in a secure location. If you set up Telegram notifications, do not publish tokens publicly.

⚠️ Note: Keep the JSON file of the Google service account in an inaccessible folder. Never share it or upload it to public repositories.

Tip: Create a project folder on the system disk so paths are short and without spaces. For example, C:/wb_ozon_monitor on Windows or /home/username/wb_ozon_monitor on Linux.

Basic Concepts

Before diving into practice, let's briefly cover key terms and principles so you understand why we take certain steps.

  • HTTP request — a call to a web page or API. We request HTML or JSON, then extract the required data.
  • Parsing — extracting data from HTML/JSON. We will parse price, discount, rating, reviews, etc.
  • Mobile proxies — intermediaries for requests. They mask your IP, reducing the risk of being blocked. IP rotation between request batches increases reliability.
  • Google Sheets API — an interface for writing data to Google Sheets. A service account allows the script to add rows and create charts.
  • Schedule — automatic script execution at specific times, allowing monitoring to function without your involvement.
  • Telegram bot — sending notifications via a simple HTTP request to the Telegram API when there are significant price changes.

It is important to understand that the layout of marketplace pages can change at any moment. Therefore, we will implement two levels of resilience: careful request headers and flexible parsing code with multiple data extraction options.

⚠️ Note: Before mass monitoring, familiarize yourself with the terms of use of the sites and the robots.txt of the respective marketplaces. Use moderate request frequency, correct headers, and delays. Avoid trying to bypass payment barriers, captchas, and do not use aggressive methods.

Tip: During debugging, start small: 1–2 items, one run every 6–12 hours. Once you confirm stability, gradually increase frequency and the number of items.

Step 1: Installing Python and Setting Up the Environment

Stage Goal

Install Python 3.11+, create a project, and prepare a virtual environment with the necessary libraries.

Step-by-Step Instructions

  1. Visit the Python download page and download version 3.11 or newer for your OS. Install it while checking the option to add Python to PATH.
  2. Create a project folder. On Windows, create C:/wb_ozon_monitor. On Linux, create /home/username/wb_ozon_monitor.
  3. Open the terminal or command prompt. Navigate to the project folder with the command: on Windows type cd C:/wb_ozon_monitor, on Linux type cd /home/username/wb_ozon_monitor.
  4. Create a virtual environment. On Windows, type python -m venv venv. On Linux, type python3 -m venv venv.
  5. Activate the environment. On Windows, type venv/Scripts/activate. On Linux, type source venv/bin/activate.
  6. Update the package manager. Type pip install --upgrade pip.
  7. Install libraries. Type pip install requests beautifulsoup4 gspread oauth2client schedule.
  8. Create a requirements.txt file. Add lines with library names: requests, beautifulsoup4, gspread, oauth2client, schedule.

Important Notes

Important: Activate the virtual environment every time before running the script to use the correct library versions.

Tip: If you have multiple Python versions, ensure you are using 3.11+ by checking python --version or python3 --version.

Expected Result

Command python --version shows 3.11+; the pip list command shows installed libraries; the project folder contains venv and requirements.txt.

✅ Check: Type python -c "import requests, bs4, gspread, oauth2client, schedule; print('ok')". It should return ok.

Problems and Solutions

  • Python not found: Python was not added to PATH during installation. Reinstall with the Add Python to PATH option checked.
  • venv does not activate: check the path to the activation script. On Windows, run the command in PowerShell: .\venv\Scripts\Activate.ps1, and allow script execution if necessary.
  • No permissions for installation: run the terminal as an administrator or use venv as instructed.

Step 2: Project Configuration and Secure Data Storage

Stage Goal

Create a configuration file with products, proxies, Telegram, and Google settings, and prepare the project structure.

Project Structure

  • wb_ozon_monitor/
  • venv/
  • monitor.py (main script)
  • config.json (settings)
  • state.json (previous price cache)
  • credentials.json (Google service account file, to be added later)

Step-by-Step Instructions

  1. In the project folder, create a config.json file.
  2. Open config.json in the editor and add a sample configuration line by line:
  • {
  • "google": {
  • "spreadsheet_name": "WB_Ozon_Monitor",
  • "worksheet_data": "data",
  • "worksheet_charts": "charts"
  • },
  • "telegram": {
  • "bot_token": "YOUR_BOT_TOKEN",
  • "chat_id": "YOUR_CHAT_ID",
  • "price_change_threshold_percent": 5
  • },
  • "proxy": {
  • "http": "http://user:pass@host:port",
  • "https": "http://user:pass@host:port",
  • "rotation_url": "URL_FOR_ROTATING_IP_FROM_mobileproxy.space_ACCOUNT"
  • },
  • "request": {
  • "user_agents": [
  • "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0 Safari/537.36",
  • "Mozilla/5.0 (Macintosh; Intel Mac OS X 13_0) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Safari/605.1.15",
  • "Mozilla/5.0 (Linux; Android 13; Mobile) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0 Mobile Safari/537.36"
  • ],
  • "min_delay_sec": 1.5,
  • "max_delay_sec": 4.0
  • },
  • "products": [
  • {"marketplace": "wildberries", "sku": "12345678", "url": "https://www.wildberries.ru/catalog/12345678/detail.aspx", "category_url": ""},
  • {"marketplace": "ozon", "sku": "987654321", "url": "https://www.ozon.ru/product/987654321/", "category_url": "https://www.ozon.ru/category/naushniki-14500/?sorting=rating"}
  • ],
  • "schedule": {
  • "interval_minutes": 360
  • }
  • }
  1. Save the config.json file.
  2. Create an empty state.json file and place {} in it.

Important Notes

Important: Ensure that the values for URL and SKU are correct. The SKU should match the actual product IDs.

Tip: For Ozon, add the category_url of the category where you want to measure the product's position. For Wildberries, you can skip the category_url if position tracking is not needed.

Expected Result

The files config.json and state.json are created. The config.json contains your products and settings for proxies, Telegram, and Google Sheets.

✅ Check: Open config.json and ensure that the JSON is valid: all quotes are paired, commas are correctly placed, and the last key-value pair does not end with a comma.

Problems and Solutions

  • JSON reading error: check the commas and quotes. Use an online JSON validator or the built-in validation in your editor.
  • Incorrect URLs: open links in your browser and ensure that the product pages are accessible without authentication.

Step 3: Setting Up Google Sheets and Service Account

Stage Goal

Create a Google service account, grant access to the spreadsheet, and prepare sheets for data logging and charts.

Step-by-Step Instructions

  1. Open Google Cloud Console, create a project or use an existing one.
  2. Enable Google Sheets and Google Drive API for your project. Find these services in the API catalog and click Enable.
  3. Create a service account: navigate to IAM & admin, Service accounts, Create service account. Provide a name; you don't need to assign roles globally, just the key file is sufficient.
  4. Create a JSON key for the service account. Download credentials.json and place it in the wb_ozon_monitor project folder.
  5. Create a Google Sheets document with the name specified in config.json under spreadsheet_name, e.g., WB_Ozon_Monitor.
  6. Open this sheet and create two sheets named data and charts. If these sheets already exist by default, rename them.
  7. Copy the email of the service account from Google Cloud Console (it ends with gserviceaccount.com).
  8. Share the Google Sheets with this email, granting Editor rights.
  9. Prepare the headers in the data sheet. Insert the following into the first row by columns: timestamp, marketplace, sku, name, price, discount_percent, rating, reviews, availability_total, warehouses_in_stock, ozon_card_price, category_rank, url.

Important Notes

Important: If you don't share the sheet with the service account, data logging will be impossible.

Tip: Name the sheets exactly as in config.json. This will eliminate errors when writing and generating charts.

Expected Result

The credentials.json file is in the project folder, the WB_Ozon_Monitor spreadsheet exists, the service account has permissions, the data sheet contains header rows, and the charts sheet is empty.

✅ Check: Open the sheet in Incognito mode. Make sure access is active and the service account appears in the user list.

Problems and Solutions

  • PERMISSION_DENIED error: access for the service account is not enabled. Add the account email in the sharing settings of the spreadsheet.
  • credentials.json file not found: check the path and filename. It should match what is specified in the script.

Step 4: Connecting Mobile Proxies and IP Rotation

Stage Goal

Connect mobileproxy.space to the script to change IPs before batches of requests to reduce the risk of blocks.

Step-by-Step Instructions

  1. Log in to your mobileproxy.space account.
  2. Create or select an existing mobile proxy. Copy the address, port, username, and password.
  3. Copy the rotation URL for IP changes from the settings of your proxy. This is usually a ready link for HTTP requests that triggers IP rotation.
  4. Open config.json. In the proxy section, insert your http and https with username and password, as well as the rotation_url from your account.
  5. Save config.json.

Using Proxies in the Code

The script will create a requests session with the proxy, send proper headers, apply delays, and change IPs through the rotation_url before each batch of product requests. This is a safe, moderate strategy.

Tip: Configure the rotation not too frequently to avoid raising suspicion. For example, once per batch of products or once hourly.

Expected Result

The config.json is correctly filled with proxy information and the rotation_url. The proxy is accessible, and IP rotation is triggered by the URL from your account.

✅ Check: Later, when we run the script, you will see confirmation of the rotation_url call in the logs and successful requests through the proxy.

Problems and Solutions

  • IP not changing: ensure you are using the correct rotation_url from your account.
  • Authentication failure: check the accuracy of the username and password in the proxy string.

⚠️ Note: Do not trigger rotation too frequently. Excessive switching can lead to delays and connection instability.

Step 5: Parsing Wildberries and Ozon: Logic and Code

Stage Goal

Create the main script monitor.py that takes a list of products, collects data from marketplaces, processes the results, and prepares them for logging in Google Sheets.

Script Architecture

  • Loading config.json and state.json.
  • Requests session with proxies and headers.
  • IP rotation before a batch of requests.
  • Wildberries and Ozon parsing functions.
  • Logging function to Google Sheets.
  • Telegram notifications function.
  • Main loop and schedule.

Creating monitor.py File

  1. Create the monitor.py file in your project folder.
  2. Insert code lines in order as indicated below. If a line is long, copy it in full. After pasting, save the file.

Imports and Utilities

  1. import json, time, random, datetime, re, os
  2. from typing import Dict, Any, List
  3. import requests
  4. from bs4 import BeautifulSoup
  5. import gspread
  6. from oauth2client.service_account import ServiceAccountCredentials
  7. import schedule

Loading Configuration and State

  1. def load_json(path: str) -> Dict[str, Any]:
  2. with open(path, 'r', encoding='utf-8') as f: return json.load(f)
  3. def save_json(path: str, data: Dict[str, Any]) -> None:
  4. with open(path, 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=2)
  5. CONFIG = load_json('config.json')
  6. STATE_PATH = 'state.json'
  7. if not os.path.exists(STATE_PATH): save_json(STATE_PATH, {})
  8. STATE = load_json(STATE_PATH)

Session with Proxy and Headers

  1. def pick_user_agent(cfg: Dict[str, Any]) -> str:
  2. return random.choice(cfg['request']['user_agents'])
  3. def make_session(cfg: Dict[str, Any]) -> requests.Session:
  4. s = requests.Session()
  5. s.proxies = {'http': cfg['proxy']['http'], 'https': cfg['proxy']['https']}
  6. s.headers.update({'User-Agent': pick_user_agent(cfg), 'Accept-Language': 'ru-RU,ru;q=0.9', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'})
  7. s.timeout = 30
  8. return s
  9. def rotate_ip(cfg: Dict[str, Any]) -> None:
  10. url = cfg['proxy'].get('rotation_url')
  11. if not url: return
  12. try:
  13. requests.get(url, timeout=20)
  14. except Exception as e:
  15. print(f'Rotation error: {e}')
  16. def smart_delay(cfg: Dict[str, Any]) -> None:
  17. d = random.uniform(cfg['request']['min_delay_sec'], cfg['request']['max_delay_sec'])
  18. time.sleep(d)

Parsing Wildberries

  1. def parse_wb(session: requests.Session, item: Dict[str, Any]) -> Dict[str, Any]:
  2. sku = item['sku']
  3. url = item['url']
  4. data = {'marketplace': 'wildberries', 'sku': sku, 'url': url, 'name': None, 'price': None, 'discount_percent': None, 'rating': None, 'reviews': None, 'availability_total': None, 'warehouses_in_stock': None, 'ozon_card_price': None, 'category_rank': None}
  5. try:
  6. api_url = f'https://card.wb.ru/cards/detail?nm={sku}'
  7. r = session.get(api_url, timeout=30)
  8. if r.status_code == 200 and r.headers.get('Content-Type','').lower().find('json') != -1:
  9. j = r.json()
  10. products = j.get('data', {}).get('products', [])
  11. if products:
  12. p = products[0]
  13. name = p.get('name')
  14. priceU = p.get('priceU') or 0
  15. salePriceU = p.get('salePriceU') or 0
  16. price = round((salePriceU or priceU)/100, 2) if (salePriceU or priceU) else None
  17. base_price = round(priceU/100, 2) if priceU else None
  18. discount = None
  19. if base_price and price and base_price > 0:
  20. discount = round(100*(base_price - price)/base_price, 2)
  21. rating = p.get('rating')
  22. reviews = p.get('feedbacks')
  23. sizes = p.get('sizes', [])
  24. total = 0
  25. wh_in_stock = 0
  26. for s in sizes:
  27. stocks = s.get('stocks', [])
  28. if stocks:
  29. wh_in_stock += sum(1 for st in stocks if st.get('qty',0) > 0)
  30. total += sum(st.get('qty',0) for st in stocks)
  31. data.update({'name': name, 'price': price, 'discount_percent': discount, 'rating': rating, 'reviews': reviews, 'availability_total': total, 'warehouses_in_stock': wh_in_stock})
  32. if not data['name']:
  33. r2 = session.get(url, timeout=30)
  34. soup = BeautifulSoup(r2.text, 'html.parser')
  35. title = soup.find('h1')
  36. if title: data['name'] = title.get_text(strip=True)
  37. m = re.search(r'"rating":\s*(\d+(?:\.\d+)?)', r2.text)
  38. if m: data['rating'] = float(m.group(1))
  39. except Exception as e:
  40. print(f'WB parse error for {sku}: {e}')
  41. return data

Parsing Ozon

  1. def parse_ozon(session: requests.Session, item: Dict[str, Any]) -> Dict[str, Any]:
  2. sku = item['sku']
  3. url = item['url']
  4. cat_url = item.get('category_url') or ''
  5. data = {'marketplace': 'ozon', 'sku': sku, 'url': url, 'name': None, 'price': None, 'discount_percent': None, 'rating': None, 'reviews': None, 'availability_total': None, 'warehouses_in_stock': None, 'ozon_card_price': None, 'category_rank': None}
  6. try:
  7. r = session.get(url, timeout=30)
  8. html = r.text
  9. soup = BeautifulSoup(html, 'html.parser')
  10. ld_nodes = soup.find_all('script', {'type':'application/ld+json'})
  11. for n in ld_nodes:
  12. try:
  13. j = json.loads(n.string or '{}')
  14. if isinstance(j, list):
  15. for jj in j:
  16. if isinstance(jj, dict) and jj.get('@type') == 'Product':
  17. name = jj.get('name')
  18. offers = jj.get('offers', {})
  19. price = offers.get('price')
  20. agg = jj.get('aggregateRating', {})
  21. rating = agg.get('ratingValue')
  22. reviews = agg.get('reviewCount') or agg.get('ratingCount')
  23. if name and not data['name']: data['name'] = name
  24. if price and not data['price']:
  25. try: data['price'] = float(price)
  26. except: pass
  27. if rating and not data['rating']:
  28. try: data['rating'] = float(rating)
  29. except: pass
  30. if reviews and not data['reviews']:
  31. try: data['reviews'] = int(reviews)
  32. except: pass
  33. elif isinstance(j, dict) and j.get('@type') == 'Product':
  34. name = j.get('name')
  35. offers = j.get('offers', {})
  36. price = offers.get('price')
  37. agg = j.get('aggregateRating', {})
  38. rating = agg.get('ratingValue')
  39. reviews = agg.get('reviewCount') or agg.get('ratingCount')
  40. if name and not data['name']: data['name'] = name
  41. if price and not data['price']:
  42. try: data['price'] = float(price)
  43. except: pass
  44. if rating and not data['rating']:
  45. try: data['rating'] = float(rating)
  46. except: pass
  47. if reviews and not data['reviews']:
  48. try: data['reviews'] = int(reviews)
  49. except: pass
  50. except Exception:
  51. pass
  52. m_card = re.search(r'"cardPrice"\s*:\s*\{[^}]*?"price"\s*:\s*(\d+(?:\.\d+)?)', html)
  53. if m_card:
  54. try: data['ozon_card_price'] = float(m_card.group(1))
  55. except: pass
  56. if not data['name']:
  57. title = soup.find('h1')
  58. if title: data['name'] = title.get_text(strip=True)
  59. if cat_url:
  60. data['category_rank'] = find_rank_in_category(session, cat_url, sku)
  61. except Exception as e:
  62. print(f'Ozon parse error for {sku}: {e}')
  63. return data

Finding Rank in Ozon Category

  1. def find_rank_in_category(session: requests.Session, category_url: str, sku: str, max_pages: int = 5) -> Any:
  2. try:
  3. rank = None
  4. pos_counter = 0
  5. for page in range(1, max_pages+1):
  6. url = category_url
  7. if 'page=' in url:
  8. url = re.sub(r'page=\d+', f'page={page}', url)
  9. else:
  10. sep = '&' if '?' in url else '?'
  11. url = f'{url}{sep}page={page}'
  12. r = session.get(url, timeout=30)
  13. html = r.text
  14. ids = re.findall(r'"productId"\s*:\s*(\d+)', html)
  15. if not ids: ids = re.findall(r'"id"\s*:\s*(\d+)', html)
  16. for pid in ids:
  17. pos_counter += 1
  18. if pid == str(sku):
  19. rank = pos_counter
  20. return rank
  21. smart_delay(CONFIG)
  22. return rank
  23. except Exception as e:
  24. print(f'Rank error: {e}')
  25. return None

Universal Data Collection from Products

  1. def collect_items(cfg: Dict[str, Any]) -> List[Dict[str, Any]]:
  2. rotate_ip(cfg)
  3. session = make_session(cfg)
  4. results = []
  5. for item in cfg['products']:
  6. try:
  7. session.headers.update({'User-Agent': pick_user_agent(cfg)})
  8. if item['marketplace'] == 'wildberries':
  9. res = parse_wb(session, item)
  10. elif item['marketplace'] == 'ozon':
  11. res = parse_ozon(session, item)
  12. else:
  13. continue
  14. results.append(res)
  15. except Exception as e:
  16. print(f'Collect error: {e}')
  17. smart_delay(cfg)
  18. return results

Connecting to Google Sheets

  1. def get_gsheets_client() -> gspread.Client:
  2. scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
  3. creds = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)
  4. client = gspread.authorize(creds)
  5. return client
  6. def write_to_sheet(cfg: Dict[str, Any], rows: List[List[Any]]) -> None:
  7. client = get_gsheets_client()
  8. sh = client.open(cfg['google']['spreadsheet_name'])
  9. ws = None
  10. try: ws = sh.worksheet(cfg['google']['worksheet_data'])
  11. except: ws = sh.add_worksheet(title=cfg['google']['worksheet_data'], rows=1000, cols=20)
  12. ws.append_rows(rows, value_input_option='RAW')

Creating a Chart in Google Sheets

  1. def ensure_chart(cfg: Dict[str, Any]) -> None:
  2. client = get_gsheets_client()
  3. sh = client.open(cfg['google']['spreadsheet_name'])
  4. data_title = cfg['google']['worksheet_data']
  5. charts_title = cfg['google']['worksheet_charts']
  6. try: charts_ws = sh.worksheet(charts_title)
  7. except: charts_ws = sh.add_worksheet(title=charts_title, rows=20, cols=20)
  8. body = {
  9. 'requests': [{
  10. 'addChart': {
  11. 'chart': {
  12. 'spec': {
  13. 'title': 'Price Dynamics',
  14. 'basicChart': {
  15. 'chartType': 'LINE',
  16. 'legendPosition': 'BOTTOM_LEGEND',
  17. 'axis': [ {'position':'BOTTOM_AXIS','title':'timestamp'}, {'position':'LEFT_AXIS','title':'price'} ],
  18. 'domains': [ { 'domain': { 'sourceRange': { 'sources': [ { 'sheetId': sh.worksheet(data_title).id, 'startRowIndex': 1, 'startColumnIndex': 0, 'endColumnIndex': 1 } ] } } } ],
  19. 'series': [ { 'series': { 'sourceRange': { 'sources': [ { 'sheetId': sh.worksheet(data_title).id, 'startRowIndex': 1, 'startColumnIndex': 4, 'endColumnIndex': 5 } ] } }, 'targetAxis':'LEFT_AXIS' } ]
  20. }
  21. },
  22. 'position': { 'newSheet': False, 'overlayPosition': { 'anchorCell': { 'sheetId': charts_ws.id, 'rowIndex': 0, 'columnIndex': 0 }, 'offsetXPixels': 0, 'offsetYPixels': 0, 'widthPixels': 800, 'heightPixels': 400 } }
  23. }
  24. }
  25. }]
  26. }
  27. try:
  28. sh.batch_update(body)
  29. except Exception as e:
  30. print(f'Chart creation skipped or already exists: {e}')

Telegram Notifications

  1. def notify(cfg: Dict[str, Any], text: str) -> None:
  2. token = cfg['telegram'].get('bot_token')
  3. chat_id = cfg['telegram'].get('chat_id')
  4. if not token or not chat_id: return
  5. url = f'https://api.telegram.org/bot{token}/sendMessage'
  6. try: requests.post(url, json={'chat_id': chat_id, 'text': text}, timeout=20)
  7. except Exception as e: print(f'Telegram error: {e}')

Price Comparison and Notification Generation

  1. def handle_notifications(cfg: Dict[str, Any], items: List[Dict[str, Any]]) -> None:
  2. threshold = cfg['telegram'].get('price_change_threshold_percent', 0)
  3. if not threshold: return
  4. global STATE
  5. changed = []
  6. ts = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
  7. for it in items:
  8. key = f"{it['marketplace']}_{it['sku']}"
  9. new_price = it.get('price')
  10. old_price = None
  11. if key in STATE: old_price = STATE[key].get('price')
  12. if new_price and old_price and old_price > 0:
  13. diff = ((new_price - old_price)/old_price)*100
  14. if abs(diff) >= threshold:
  15. changed.append((it, old_price, new_price, diff))
  16. STATE[key] = {'price': new_price, 'updated': ts}
  17. if changed:
  18. lines = []
  19. for it, op, np, d in changed:
  20. lines.append(f"{it['marketplace']} sku {it['sku']}: {op} -> {np} ({round(d,2)}%)")
  21. msg = 'Price Changes:\n' + '\n'.join(lines)
  22. notify(cfg, msg)
  23. save_json(STATE_PATH, STATE)

Transforming Results for Logging to the Sheet

  1. def to_rows(items: List[Dict[str, Any]]) -> List[List[Any]]:
  2. ts = datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')
  3. rows = []
  4. for it in items:
  5. row = [ts, it.get('marketplace'), it.get('sku'), it.get('name'), it.get('price'), it.get('discount_percent'), it.get('rating'), it.get('reviews'), it.get('availability_total'), it.get('warehouses_in_stock'), it.get('ozon_card_price'), it.get('category_rank'), it.get('url')]
  6. rows.append(row)
  7. return rows

Main Run

  1. def run_once():
  2. items = collect_items(CONFIG)
  3. rows = to_rows(items)
  4. if rows:
  5. write_to_sheet(CONFIG, rows)
  6. ensure_chart(CONFIG)
  7. handle_notifications(CONFIG, items)
  8. if __name__ == '__main__':
  9. interval = CONFIG.get('schedule',{}).get('interval_minutes', 360)
  10. if interval and interval > 0:
  11. schedule.every(interval).minutes.do(run_once)
  12. run_once()
  13. while True:
  14. schedule.run_pending()
  15. time.sleep(1)
  16. else:
  17. run_once()

Important Notes

Important: We use moderate headers, random delays, and IP rotation. This reduces the risk of blocks and adheres to ethical practices.

Tip: If you see unexpected values or empty fields, temporarily print r.status_code and r.text for diagnostics, then disable extra logging.

Expected Result

The monitor.py file is created. It is ready to run and contains all key components: parsing, logging to Sheets, notifications, and scheduling.

✅ Check: Run python monitor.py from the project folder. The script should complete one cycle, log a row in the data sheet, attempt to create a chart, and send notifications if necessary.

Problems and Solutions

  • Import error: ensure the venv is active and libraries are installed.
  • Access error to the sheet: verify that credentials.json is correct and the sheet is shared with the service account.
  • Parsing returns None: verify SKU and URL, check if page structures have changed. Set up alternative parsing paths via ld+json and regular expressions.

Step 6: Automatically Creating Charts in Google Sheets

Stage Goal

Add a chart of price dynamics to the sheet that will update itself as new data arrives.

Step-by-Step Instructions

  1. Ensure the data sheet contains header rows in the first row and at least one row of data below it.
  2. Run python monitor.py manually to invoke ensure_chart and add the chart.
  3. Open the charts sheet and locate the inserted chart titled Price Dynamics.
  4. If necessary, manually edit the chart in the Sheets interface: select desired series, filter by product. This does not affect automatic data updates.

Important Notes

Important: The sample code creates a basic line chart for price. If you want separate charts for each SKU, create additional charts manually or modify the addChart request to add filtering and new series.

Tip: Create a filterable table and pivot sheets in Sheets to build individual charts without altering the code.

Expected Result

A chart has appeared on the charts sheet. With each new record, a point will be automatically added.

✅ Check: Add another record by running the script again. Ensure that the chart updates with new points.

Problems and Solutions

  • The chart is not created: it may already exist or there are insufficient permissions. Remove the old chart and rerun the script. Check the service account's permissions.
  • Incorrect data on the axis: verify that the timestamp is in the first column and the price is in the fifth.

Step 7: Scheduled Auto-Start on Windows and Linux

Stage Goal

Set up automatic script launches on a schedule to allow monitoring to function without manual intervention.

Windows: Task Scheduler

  1. Open Task Scheduler.
  2. Create a task, choosing Create Basic Task.
  3. Specify a name, e.g., WB Ozon Monitor.
  4. Select frequency, e.g., Daily.
  5. Specify the time for the first launch.
  6. Under Action, select Start a Program.
  7. In the Program field, specify the path to python.exe from venv, e.g., C:\wb_ozon_monitor\venv\Scripts\python.exe.
  8. In the Add arguments field, specify monitor.py.
  9. In the Start in field, specify C:\wb_ozon_monitor.
  10. Save the task, optionally enabling it to run on battery power if desired.

Linux: cron

  1. Open the terminal and enter crontab -e.
  2. Add a line considering the path to your interpreter and script. For example:
  • 0 */6 * * * /home/username/wb_ozon_monitor/venv/bin/python /home/username/wb_ozon_monitor/monitor.py > /home/username/wb_ozon_monitor/cron.log 2>&1
  1. Save and exit the editor. Cron will run the script every 6 hours.

Tip: Check that the task has the correct working directory and permissions to write to state.json files and logs.

Expected Result

The script runs automatically on schedule. The log file or the sheet indicates new entries at the required times.

✅ Check: Wait for one schedule cycle and check that a new row has appeared in the table.

Problems and Solutions

  • The task does not start: on Windows, verify paths in the fields. On Linux, check permissions, crontab paths, and environment variables.
  • Libraries not found: use Python from venv rather than the system Python.

Step 8: Telegram Notifications for Price Changes

Stage Goal

Receive notifications if the price changes by more than the specified percentage.

Step-by-Step Instructions

  1. In Telegram, find BotFather and create a bot. Save the token.
  2. Send any message to your bot.
  3. Find out your chat_id. Send a message to the bot, then use any means to get chat_id, such as adding the bot to a personal chat and using web services to determine chat_id, or temporarily enable logging of requests to Telegram and extract id from responses. The easiest way is to add the bot to a created channel and get the channel id through settings.
  4. Open config.json and fill in bot_token, chat_id, and the price_change_threshold_percent threshold, e.g., 5.
  5. Save the configuration and run python monitor.py. Upon a significant price change compared to the previous value, you will receive a notification.

Tip: For testing, temporarily set the threshold to 0 or 0.1 to verify notification functionality. Then revert to the actual threshold.

Expected Result

Upon a price change exceeding the threshold, a notification should arrive in Telegram detailing: marketplace, SKU, old and new price, percentage.

✅ Check: Manually change the state in state.json by reducing the old price for one item and run the script. A notification should arrive.

Problems and Solutions

  • Notifications not arriving: check the accuracy of the token and chat_id. Ensure the bot is not blocked and that you have interacted with it.
  • Too many notifications: increase the threshold or limit the frequency of runs.

Step 9: Ensuring Resilience and Ethical Bypassing of Anti-Bot Protection

Stage Goal

Minimize risks of blocks and false data by configuring reasonable headers, delays, IP rotation, and backup parsing mechanisms.

Step-by-Step Instructions

  1. In config.json, add 3-5 different User-Agent strings. This simulates different device types.
  2. Set reasonable delays. For example, min_delay_sec 1.5 and max_delay_sec 4.0. This reduces site load and makes behavior appear natural.
  3. Use IP rotation before a batch. This minimizes the risk of being filtered by IP and helps distribute traffic evenly.
  4. Add a fallback path for parsing. For Wildberries, use the JSON endpoint of the product card and, if necessary, fallback to HTML. For Ozon, extract data from ld+json and additional JSON structures on the page.
  5. Limit the number of products in a single batch. Preference should be given to 10-20 items per cycle rather than hundreds at once.
  6. Monitor response codes. If you see 429 or 403, increase delays and reduce frequency.

Tip: Maintain a light log in a file called cron.log or monitor.log to see when and why errors occurred. This will help respond quickly to changes in page structures.

⚠️ Note: Do not use aggressive methods to bypass protections, such as solving captchas automatically, hacking closed APIs, spoofing browser fingerprints, or mass parallelism. Respect the terms of service for the platforms.

Tip: In case of failures, temporarily disable proxies for diagnostics: this will help you determine whether the issue is related to proxies or website changes.

Results Verification

Checklist

  • Python 3.11+ is installed and libraries are in place.
  • Files config.json, credentials.json, and state.json are created.
  • The service account has access to the sheet, and the data sheet contains headers.
  • monitor.py runs without errors and logs rows to Sheets.
  • The Price Dynamics chart displays on the charts sheet and updates correctly.
  • The scheduled run operates on your OS.
  • Telegram notifications arrive for significant changes.

How to Test

  1. Run python monitor.py manually and check that a row appeared in data.
  2. Change the Telegram threshold to 0.1 and edit state.json to provoke a notification.
  3. Check cron.log or the Task Scheduler for confirmation of automatic runs.

Success Indicators

  • Data appears on schedule without interruptions.
  • The chart shows a smooth line of prices with new points after each run.
  • Notifications arrive timely, without false alarms.

✅ Check: If all the above points are executed, your monitoring system is fully operational.

Common Issues and Solutions

  • Problem: Google Sheets access error. Reason: the service account is not added as an editor. Solution: share the sheet with the email of the service account and try again.
  • Problem: Empty price or rating fields. Reason: page structures have changed or the script did not find the necessary block. Solution: update parsing, add alternative selectors, check ld+json, and ensure fallback through regular expressions.
  • Problem: 403 or 429 errors on requests. Reason: requests are too frequent, headers are too uniform, or rotation is not implemented. Solution: increase delays, expand the User-Agent list, and use IP rotation less frequently but consistently.
  • Problem: Telegram notifications are not received. Reason: incorrect token or chat_id. Solution: recreate the bot in BotFather, check chat_id, and ensure you’re messaging the bot in that chat.
  • Problem: Cron is running but no data. Reason: incorrect paths or using system Python without the libraries. Solution: specify the full path to the Python from venv and the script file, and check write permissions.
  • Problem: Chart duplication. Reason: attempting to create a chart that already exists. Solution: remove the old chart manually or leave it; the code will skip creation on error.
  • Problem: JSONDecodeError errors when reading state.json. Reason: the file is corrupted due to manual editing. Solution: recreate state.json with the content {}.

Additional Features

Advanced Settings

  • Filtering products for separate tables: separate products by tabs so each brand or category has its sheet.
  • Advanced charts: create multiple series on a chart to compare different SKUs or add a second chart for ratings.
  • Additional metrics: for Wildberries, add warehouse analysis grouped by wh-id, for Ozon — tracking availability or promotions by keywords.

Optimization

  • Caching responses: temporarily save JSON by SKU to analyze changes without repeated requests during debugging.
  • Batch writing to Sheets: already implemented via append_rows, use batch writing once per cycle instead of per row.
  • Flexible scheduling: launch less frequently at night, and more often during the day. For example, every 6-12 hours at night, every 2-3 hours during the day.

Development Ideas

  • Comparative analysis with competitors: add several similar products and build comparative charts.
  • Signals for unavailability: notify when availability_total becomes zero.
  • Export to a database: send data to PostgreSQL or BigQuery for complex analytics.

Tip: When adding a large number of products, distribute them across several schedules or use different proxies for different groups to reduce load and risk of blocks.

FAQ

  • How to add a new product? Open config.json, add an object to the products array with fields marketplace, sku, url, and category_url if necessary. Save the file and rerun the script.
  • How to change the frequency of runs? Change interval_minutes in config.json. The lower the value, the more frequently data will be collected. Balance frequency with the risk of blocks.
  • Can it run on multiple computers? Yes, but avoid simultaneous requests to the same products. Divide the list among machines.
  • How to calculate the median price for a week? Add a pivot table in Sheets, group by SKU and date, use the median function or aggregate functions.
  • What to do if a product card is temporarily unavailable? The script will skip some fields, logging empty values or None. Check on the next run. If it persists, check the URL and SKU.
  • How to change the set of fields? In the to_rows function, add or remove fields, and update headers in the sheet. For the chart, adjust the addChart request.
  • Is it necessary to keep the script running for cron? No. Cron runs it automatically. If you use the schedule library, keep the script running constantly. Servers usually prefer cron.
  • Can it run without proxies? Yes, but the risk of 403 or 429 increases. Proxies enhance stability.
  • How to log errors? Redirect output to a file. The example in cron on Linux is already given. On Windows, specify output to a file via a bat script.

Conclusion

You’ve set up a full-fledged price monitoring system for Wildberries and Ozon using Python with mobile proxies and Google Sheets. You now have: stable collection of prices, discounts, ratings, and reviews; optional category position for Ozon; automatic logging in the spreadsheet; dynamic charts; scheduled auto-start; notifications in Telegram for significant changes. The guide has taken you from Python installation to the final dashboard, designed for long-term operation.

Next, you can expand the list of SKUs, build more analytical charts, integrate availability alerts, track competitors, and experiment with more complex prediction models. Keep the code neat, regularly check parsing accuracy, and respect the rules of the platforms.

Tip: Once a month, perform maintenance: update libraries, check the accuracy of parsing, test access to Sheets and Telegram, and review logs.