Code:

import os
import time
import json
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, JavascriptException
from webdriver_manager.chrome import ChromeDriverManager

class AviatorScraper:
    def __init__(self):
        self.SCREENSHOT_DIR = "screenshots"
        self.DATA_DIR = "data"
        self.MAX_WAIT = 30
        self.driver = None
        
        for directory in [self.SCREENSHOT_DIR, self.DATA_DIR]:
            if not os.path.exists(directory):
                os.makedirs(directory)

    def setup_driver(self):
        options = webdriver.ChromeOptions()
        options.add_argument('--no-sandbox')
        options.add_argument('--disable-dev-shm-usage')
        options.add_argument('--window-size=1920,1080')
        self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
        self.wait = WebDriverWait(self.driver, self.MAX_WAIT)

    def login(self):
        self.driver.get("https://betika.com/en-ke/login")
        print("Opened Betika login page.")

        try:
            close_modal_button = self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.close-modal")))
            close_modal_button.click()
            print("Closed modal.")
        except TimeoutException:
            print("No modal to close.")

        login_steps = [
            {
                'selector': "div.session__form__input.session__form__phone input.input",
                'action': lambda elem: elem.send_keys("0703972766"),
                'message': "Entered phone number"
            },
            {
                'selector': "div.session__form__input.session__form__password input.input",
                'action': lambda elem: elem.send_keys("ComplexPass123!"),
                'message': "Entered password"
            },
            {
                'selector': "button.session__form__button.login.button.button__secondary",
                'action': lambda elem: elem.click(),
                'message': "Clicked login button"
            }
        ]

        for step in login_steps:
            element = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, step['selector'])))
            step['action'](element)
            print(step['message'])

    def navigate_to_aviator(self):
        time.sleep(5)
        self.driver.get("https://betika.com/en-ke/aviator")
        print("Navigated to Aviator page.")
        time.sleep(10)

    def get_historical_multipliers(self):
        try:
            # JavaScript to extract historical multipliers
            js_script = """
            function extractMultipliers() {
                // Target the specific elements containing historical multipliers
                const historyElements = Array.from(document.querySelectorAll('.last-results .last-results-item'));
                
                return historyElements.map(element => ({
                    multiplier: element.textContent.trim(),
                    timestamp: new Date().toISOString(),
                    type: 'historical'
                }));
            }
            return extractMultipliers();
            """
            historical_multipliers = self.driver.execute_script(js_script)
            print(f"Found {len(historical_multipliers)} historical multipliers")
            return historical_multipliers
        except Exception as e:
            print(f"Error getting historical multipliers: {e}")
            return []

    def monitor_new_multipliers(self, duration=300):
        start_time = time.time()
        new_multipliers = []
        last_multiplier = None

        while time.time() - start_time < duration:
            try:
                js_script = """
                function getLatestMultiplier() {
                    const resultElement = document.querySelector('.last-results .last-results-item:first-child');
                    return resultElement ? resultElement.textContent.trim() : null;
                }
                return getLatestMultiplier();
                """
                current_multiplier = self.driver.execute_script(js_script)
                
                if current_multiplier and current_multiplier != last_multiplier:
                    new_multipliers.append({
                        'multiplier': current_multiplier,
                        'timestamp': datetime.now().isoformat(),
                        'type': 'new'
                    })
                    print(f"New multiplier detected: {current_multiplier}")
                    last_multiplier = current_multiplier
                
                time.sleep(1)
            except Exception as e:
                print(f"Error monitoring new multipliers: {e}")
        
        return new_multipliers

    def analyze_iframe(self, iframe_element):
        try:
            self.driver.switch_to.frame(iframe_element)
            time.sleep(2)  # Wait for iframe content to load
            
            # First, get historical multipliers
            historical_data = self.get_historical_multipliers()
            
            # Then monitor for new multipliers
            print("Monitoring for new multipliers...")
            new_data = self.monitor_new_multipliers(duration=300)  # 5 minutes
            
            return historical_data + new_data

        finally:
            self.driver.switch_to.default_content()

    def save_data(self, rounds_data):
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        filename = f'aviator_data_{timestamp}.json'
        filepath = os.path.join(self.DATA_DIR, filename)
        
        with open(filepath, 'w') as f:
            json.dump(rounds_data, f, indent=2)
        
        print(f"Saved data to {filepath}")
        return filepath

    def scrape(self):
        try:
            self.setup_driver()
            self.login()
            self.navigate_to_aviator()

            iframes = self.driver.find_elements(By.TAG_NAME, "iframe")
            print(f"Found {len(iframes)} iframes on the page.")

            all_rounds_data = []
            
            for index, iframe in enumerate(iframes):
                iframe_src = iframe.get_attribute("src")
                if "spribegaming" in iframe_src.lower():
                    print(f"Analyzing game iframe {index}")
                    rounds_data = self.analyze_iframe(iframe)
                    if rounds_data:
                        all_rounds_data.extend(rounds_data)
                        break

            if all_rounds_data:
                filepath = self.save_data(all_rounds_data)
                self.analyze_results(all_rounds_data, filepath)
            else:
                print("No multipliers found during observation period.")

        except Exception as e:
            print(f"An error occurred during scraping: {e}")
            self.driver.save_screenshot(os.path.join(self.SCREENSHOT_DIR, "error_screenshot.png"))
        
        finally:
            if self.driver:
                self.driver.quit()

    @staticmethod
    def analyze_results(rounds_data, filepath):
        multipliers = [float(round_data['multiplier'].rstrip('x')) for round_data in rounds_data]
        
        if multipliers:
            historical = [m for m in rounds_data if m['type'] == 'historical']
            new = [m for m in rounds_data if m['type'] == 'new']
            
            print("\nResults Analysis:")
            print(f"Total multipliers recorded: {len(multipliers)}")
            print(f"Historical multipliers: {len(historical)}")
            print(f"New multipliers captured: {len(new)}")
            print(f"Average multiplier: {sum(multipliers) / len(multipliers):.2f}x")
            print(f"Highest multiplier: {max(multipliers):.2f}x")
            print(f"Lowest multiplier: {min(multipliers):.2f}x")
            print(f"Data saved to: {filepath}")

def main():
    scraper = AviatorScraper()
    scraper.scrape()

if __name__ == "__main__":
    main()

Code output:

Opened Betika login page.
No modal to close.
Entered phone number
Entered password
Clicked login button
Navigated to Aviator page.
Found 11 iframes on the page.
Analyzing game iframe 0
Found 0 historical multipliers
Monitoring for new multipliers...
No multipliers found during observation period.

Please assist. Also reduce the time from 300s to 60s.