I'll help you create an automated price monitoring system that extracts prices from e-commerce websites and updates them in Google Sheets. Here's a comprehensive solution:
System Architecture
1. Google Sheets Setup and API Configuration
First, you'll need to set up Google Sheets API access:
# requirements.txt
google-auth==2.23.4
google-auth-oauthlib==1.1.0
google-auth-httplib2==0.1.1
google-api-python-client==2.108.0
selenium==4.15.2
beautifulsoup4==4.12.2
requests==2.31.0
schedule==1.2.0
pandas==2.1.3
openpyxl==3.1.2
2. Google Sheets Authentication Setup
# google_sheets_manager.py
import os
from google.oauth2 import service_account
from googleapiclient.discovery import build
from datetime import datetime
import pytz
class GoogleSheetsManager:
def __init__(self, spreadsheet_id, credentials_file):
self.spreadsheet_id = spreadsheet_id
# Setup credentials
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
creds = service_account.Credentials.from_service_account_file(
credentials_file, scopes=SCOPES)
self.service = build('sheets', 'v4', credentials=creds)
self.sheet = self.service.spreadsheets()
def read_product_links(self, range_name='Sheet1!A:B'):
"""Read product links from the sheet"""
result = self.sheet.values().get(
spreadsheetId=self.spreadsheet_id,
range=range_name
).execute()
values = result.get('values', [])
products = []
for row in values[1:]: # Skip header
if len(row) >= 2:
products.append({
'product_name': row[0],
'url': row[1]
})
return products
def append_price_data(self, data, range_name='Sheet1'):
"""Append new price data to the sheet"""
body = {
'values': data
}
result = self.sheet.values().append(
spreadsheetId=self.spreadsheet_id,
range=range_name,
valueInputOption='RAW',
body=body
).execute()
return result
3. Price Scraper for Different Websites
# price_scraper.py
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import time
import re
from urllib.parse import urlparse
class PriceScraper:
def __init__(self, headless=True):
self.setup_driver(headless)
def setup_driver(self, headless):
chrome_options = Options()
if headless:
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--disable-blink-features=AutomationControlled')
chrome_options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36')
self.driver = webdriver.Chrome(options=chrome_options)
def extract_price(self, url):
"""Main method to extract price based on website"""
domain = urlparse(url).netloc
try:
if 'blinkit.com' in domain:
return self.scrape_blinkit(url)
elif 'swiggy.com' in domain:
return self.scrape_swiggy(url)
elif 'zepto.com' in domain:
return self.scrape_zepto(url)
elif 'flipkart.com' in domain:
return self.scrape_flipkart(url)
else:
return None, "Unsupported website"
except Exception as e:
return None, str(e)
def scrape_blinkit(self, url):
"""Scrape price from Blinkit"""
self.driver.get(url)
time.sleep(3)
try:
# Wait for price element
price_element = WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, '[class*="price"]'))
)
price_text = price_element.text
price = self.clean_price(price_text)
return price, "Success"
except Exception as e:
return None, f"Blinkit scraping error: {str(e)}"
def scrape_swiggy(self, url):
"""Scrape price from Swiggy"""
self.driver.get(url)
time.sleep(3)
try:
# Swiggy uses different selectors for Instamart
price_element = WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, '[class*="rupee"]'))
)
price_text = price_element.text
price = self.clean_price(price_text)
return price, "Success"
except Exception as e:
return None, f"Swiggy scraping error: {str(e)}"
def scrape_zepto(self, url):
"""Scrape price from Zepto"""
self.driver.get(url)
time.sleep(3)
try:
# Look for price in Zepto's structure
price_element = WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, '[class*="price"], [class*="amount"]'))
)
price_text = price_element.text
price = self.clean_price(price_text)
return price, "Success"
except Exception as e:
return None, f"Zepto scraping error: {str(e)}"
def scrape_flipkart(self, url):
"""Scrape price from Flipkart"""
self.driver.get(url)
time.sleep(2)
try:
# Flipkart price selector
price_element = WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, 'div._30jeq3'))
)
price_text = price_element.text
price = self.clean_price(price_text)
return price, "Success"
except Exception as e:
return None, f"Flipkart scraping error: {str(e)}"
def clean_price(self, price_text):
"""Extract numeric price from text"""
# Remove currency symbols and extract numbers
price = re.findall(r'[\d,]+\.?\d*', price_text)
if price:
return float(price[0].replace(',', ''))
return None
def close(self):
"""Close the browser"""
self.driver.quit()
4. Main Automation Script
# price_monitor.py
import schedule
import time
from datetime import datetime
import pytz
from google_sheets_manager import GoogleSheetsManager
from price_scraper import PriceScraper
import logging
# Setup logging
logging.basicConfig(
filename='price_monitor.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
class PriceMonitor:
def __init__(self, spreadsheet_id, credentials_file):
self.sheets_manager = GoogleSheetsManager(spreadsheet_id, credentials_file)
self.timezone = pytz.timezone('Asia/Kolkata') # Adjust to your timezone
def run_price_check(self):
"""Main function to check prices and update sheet"""
logging.info("Starting price check...")
# Initialize scraper
scraper = PriceScraper(headless=True)
try:
# Get product links from sheet
products = self.sheets_manager.read_product_links()
# Prepare data to append
new_data = []
current_time = datetime.now(self.timezone)
for product in products:
logging.info(f"Checking price for: {product['product_name']}")
price, status = scraper.extract_price(product['url'])
row_data = [
product['product_name'],
product['url'],
price if price else 'N/A',
current_time.strftime('%Y-%m-%d'),
current_time.strftime('%H:%M:%S'),
status
]
new_data.append(row_data)
# Small delay between requests
time.sleep(2)
# Update Google Sheet
if new_data:
self.sheets_manager.append_price_data(new_data)
logging.info(f"Successfully updated {len(new_data)} prices")
except Exception as e:
logging.error(f"Error during price check: {str(e)}")
finally:
scraper.close()
def schedule_jobs(self):
"""Schedule the price checks"""
# Schedule for 9 AM, 2 PM, and 8 PM
schedule.every().day.at("09:00").do(self.run_price_check)
schedule.every().day.at("14:00").do(self.run_price_check)
schedule.every().day.at("20:00").do(self.run_price_check)
logging.info("Scheduled jobs for 9 AM, 2 PM, and 8 PM")
def start(self):
"""Start the monitoring system"""
logging.info("Price monitoring system started")
# Run once immediately
self.run_price_check()
# Schedule future runs
self.schedule_jobs()
# Keep the script running
while True:
schedule.run_pending()
time.sleep(60) # Check every minute
5. Main Entry Point
# main.py
from price_monitor import PriceMonitor
import os
def main():
# Configuration
SPREADSHEET_ID = 'your-google-sheet-id' # Get from sheet URL
CREDENTIALS_FILE = 'credentials.json' # Your service account key file
# Create and start monitor
monitor = PriceMonitor(SPREADSHEET_ID, CREDENTIALS_FILE)
monitor.start()
if __name__ == "__main__":
main()
Setup Instructions
1. Google Sheets API Setup:
- Go to Google Cloud Console
- Create a new project or select existing
- Enable Google Sheets API
- Create a service account and download credentials JSON
- Share your Google Sheet with the service account email
2. Google Sheet Structure:
Create a sheet with these columns:
- Column A: Product Name
- Column B: Product URL
- Column C: Price
- Column D: Date
- Column E: Time
- Column F: Status
3. Install Dependencies:
pip install -r requirements.txt
4. Install Chrome Driver:
# For Ubuntu/Debian
sudo apt-get update
sudo apt-get install chromium-chromedriver
# For Windows, download from: https://chromedriver.chromium.org/
5. Run the Script:
python main.py
Running as a Background Service
For Windows (Task Scheduler):
- Create a batch file
run_price_monitor.bat:
@echo off
cd /d "C:\path\to\your\project"
python main.py
- Use Task Scheduler to run this batch file at system startup
For Linux (systemd):
Create /etc/systemd/system/price-monitor.service:
[Unit]
Description=Price Monitor Service
After=network.target
[Service]
Type=simple
User=your-username
WorkingDirectory=/path/to/your/project
ExecStart=/usr/bin/python3 /path/to/your/project/main.py
Restart=always
[Install]
WantedBy=multi-user.target
Then enable and start:
sudo systemctl enable price-monitor.service
sudo systemctl start price-monitor.service
Important Notes:
-
Website Changes: E-commerce websites frequently update their HTML structure. You may need to update the CSS selectors periodically.
-
Rate Limiting: Add appropriate delays between requests to avoid being blocked.
-
Error Handling: The system logs errors but continues running. Check price_monitor.log regularly.
-
Legal Considerations: Check the terms of service of each website regarding web scraping.
-
Alternative Approach: Some websites provide APIs which would be more reliable than web scraping.
This system will automatically run three times daily and update your Google Sheet with current prices from the specified e-commerce platforms.