import os
import time
import logging
import hashlib
import schedule
from datetime import datetime
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 selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import StaleElementReferenceException, WebDriverException, TimeoutException, NoSuchElementException
# Configure logging
logging.basicConfig(
filename='whatsapp_unread_media_automation.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
# Directory for downloads
DOWNLOAD_DIR = r"C:\Users\sgurv\OneDrive\Documents\whatsapp_automation\downloads"
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
# Track existing files to avoid re-downloading
existing_files = {}
def safe_click(element, driver, retries=3):
"""Safely click an element with retries to handle stale references."""
for attempt in range(retries):
try:
driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", element)
element.click()
return True
except StaleElementReferenceException:
time.sleep(1)
if attempt == retries - 1:
return False
except Exception as e:
logging.error(f"Error clicking element: {str(e)}")
return False
return False
def download_blob_image(driver, element, filename, max_retries=2):
"""Download an image with a blob URL using JavaScript with retries."""
start_time = time.time()
max_duration = 30 # Maximum 30 seconds per image
for attempt in range(max_retries):
if time.time() - start_time > max_duration:
logging.warning(f"Download timeout exceeded for {filename} after {max_duration} seconds.")