DOM STRUCTURE:
text = """
        Get all multiplier values from the result history. Go to "div.result-history.disabled-on-game-focused.my-2"
        then to "div.stats.dropdown"
        then to "div.payouts-wrapper"
        then to "div.payouts-block"
        then to "app-bubble-multiplier payout ng-star-enabled"
        then to "div.bubble-multiplier.font-weight-bold"
        Extract the number that comes after "style =" but is next to the "</div>"
        Extract all numeric values that represent multipliers from each app-bubble-multiplier you can find.
        """
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, NoSuchElementException
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')
        # Optionally run headless
        # options.add_argument('--headless')
        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:
            try:
                element = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, step['selector'])))
                step['action'](element)
                print(step['message'])
            except TimeoutException:
                print(f"Timeout while trying to {step['message'].lower()}.")
                self.driver.save_screenshot(os.path.join(self.SCREENSHOT_DIR, f"login_step_timeout_{step['message'].replace(' ', '_').lower()}.png"))
                raise

    def navigate_to_aviator(self):
        time.sleep(5)  # Wait for any potential redirects or loading
        self.driver.get("https://betika.com/en-ke/aviator")
        print("Navigated to Aviator page.")
        time.sleep(10)  # Adjust this sleep if necessary based on page load time

    def get_historical_multipliers(self):
        try:
            # JavaScript to extract historical multipliers
            js_script = """
            function extractMultipliers() {
                // Update the selectors based on the current structure of the page
                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 JavascriptException as e:
            print(f"JavaScript error while getting historical multipliers: {e}")
            self.driver.save_screenshot(os.path.join(self.SCREENSHOT_DIR, "js_error_historical.png"))
            return []
        except Exception as e:
            print(f"Error getting historical multipliers: {e}")
            self.driver.save_screenshot(os.path.join(self.SCREENSHOT_DIR, "error_historical.png"))
            return []

    def monitor_new_multipliers(self, duration=60):  # Reduced duration to 60 seconds
        start_time = time.time()
        new_multipliers = []
        last_multiplier = None

        while time.time() - start_time < duration:
            try:
                js_script = """
                function getLatestMultiplier() {
                    // Update the selector based on the current structure of the page
                    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 JavascriptException as e:
                print(f"JavaScript error while monitoring new multipliers: {e}")
                self.driver.save_screenshot(os.path.join(self.SCREENSHOT_DIR, "js_error_new_multipliers.png"))
            except Exception as e:
                print(f"Error monitoring new multipliers: {e}")
                self.driver.save_screenshot(os.path.join(self.SCREENSHOT_DIR, "error_new_multipliers.png"))
        
        return new_multipliers

    def analyze_iframe(self, iframe_element):
        try:
            self.driver.switch_to.frame(iframe_element)
            print("Switched to iframe.")

            # Wait for the multipliers to load; update selector as necessary
            try:
                self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.last-results .last-results-item')))
                print("Multiplier elements found inside iframe.")
            except TimeoutException:
                print("Multiplier elements not found inside iframe within wait time.")
                self.driver.save_screenshot(os.path.join(self.SCREENSHOT_DIR, "iframe_no_multipliers.png"))
                return []

            # 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=60)  # Reduced to 60 seconds
            
            return historical_data + new_data

        except NoSuchElementException as e:
            print(f"Iframe element not found: {e}")
            self.driver.save_screenshot(os.path.join(self.SCREENSHOT_DIR, "iframe_not_found.png"))
            return []
        except Exception as e:
            print(f"Error analyzing iframe: {e}")
            self.driver.save_screenshot(os.path.join(self.SCREENSHOT_DIR, "error_analyzing_iframe.png"))
            return []
        finally:
            self.driver.switch_to.default_content()
            print("Switched back 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") or ""
                if "spribegaming" in iframe_src.lower():
                    print(f"Analyzing game iframe {index} with src: {iframe_src}")
                    rounds_data = self.analyze_iframe(iframe)
                    if rounds_data:
                        all_rounds_data.extend(rounds_data)
                        # If you expect multiple relevant iframes, don't break here
                        # break

            if not all_rounds_data:
                print("No data collected from any iframe.")
            else:
                filepath = self.save_data(all_rounds_data)
                self.analyze_results(all_rounds_data, filepath)
        
        except Exception as e:
            print(f"An error occurred during scraping: {e}")
            self.driver.save_screenshot(os.path.join(self.SCREENSHOT_DIR, "error_scraping.png"))
        
        finally:
            if self.driver:
                self.driver.quit()

    @staticmethod
    def analyze_results(rounds_data, filepath):
        # Attempt to parse multipliers to floats, removing 'x'
        multipliers = []
        for round_data in rounds_data:
            multiplier_str = round_data.get('multiplier', '').lower().replace('x', '').strip()
            try:
                multiplier = float(multiplier_str)
                multipliers.append(multiplier)
            except ValueError:
                print(f"Invalid multiplier format: {round_data.get('multiplier')}")
        
        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}")
        else:
            print("No valid multipliers found to analyze.")

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

if __name__ == "__main__":
    main()