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 ""
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
It looks like you're attempting to scrape multiplier values from the Betika Aviator game by navigating through a specific DOM structure. Let's walk through your approach and identify areas for improvement to ensure your scraper accurately extracts the desired multiplier values.
Understanding the DOM Structure
You've provided the following DOM traversal steps:
Then toapp-bubble-multiplier.payout.ng-star-enabled
Finally todiv.bubble-multiplier.font-weight-bold
Your goal is to extract the number that comes after style = but is next to the </div>, effectively capturing all numeric multiplier values within each app-bubble-multiplier component.
Issues in the Current Implementation
Upon reviewing your code, particularly the get_historical_multipliers and monitor_new_multipliers methods, there are discrepancies between the provided DOM traversal steps and the selectors used in the JavaScript executed within Selenium. Here's a summary:
Mismatch in Selectors: The JavaScript functions are targeting .last-results .last-results-item, which doesn't align with your specified DOM structure.
Focus on Iframes: Your code attempts to switch to iframes and extract data within them. However, your DOM traversal steps don't mention iframes, suggesting that multipliers are directly accessible in the main DOM.
Recommendations and Code Adjustments
1. Align Selectors with DOM Structure
To accurately extract the multipliers based on your DOM structure, adjust your JavaScript selectors to match the hierarchy you've outlined. Here's how you can modify the get_historical_multipliers method:
python
def get_historical_multipliers(self):
try:
js_script = """
function extractMultipliers() {
// Navigate through the specified DOM structure
const historyContainer = document.querySelector('div.result-history.disabled-on-game-focused.my-2');
if (!historyContainer) return [];
const statsDropdown = historyContainer.querySelector('div.stats.dropdown');
if (!statsDropdown) return [];
const payoutsWrapper = statsDropdown.querySelector('div.payouts-wrapper');
if (!payoutsWrapper) return [];
const payoutsBlock = payoutsWrapper.querySelector('div.payouts-block');
if (!payoutsBlock) return [];
const multiplierElements = payoutsBlock.querySelectorAll('app-bubble-multiplier.payout.ng-star-enabled div.bubble-multiplier.font-weight-bold');
const multipliers = [];
multiplierElements.forEach(elem => {
// Extract the number after 'style =' if present
const styleText = elem.getAttribute('style') || '';
const match = styleText.match(/(\d+(\.\d+)?)/);
if (match) {
multipliers.push(parseFloat(match[1]));
} else {
// Fallback: Try to extract number from text content
const text = elem.textContent.trim().replace('x', '');
const num = parseFloat(text);
if (!isNaN(num)) {
multipliers.push(num);
}
}
});
return multipliers.map(multiplier => ({
multiplier: multiplier,
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 []
Explanation of Changes:
Selector Hierarchy: The script now navigates through each layer of the DOM structure as you specified, ensuring accurate targeting of the multiplier elements.
Multiplier Extraction: It first attempts to extract numeric values from the style attribute. If not found, it falls back to extracting numbers directly from the text content, removing any non-numeric characters like 'x'.
Data Formatting: Each multiplier is stored as a dictionary with the multiplier value, a timestamp, and a type indicating whether it's historical or new.
2. Update monitor_new_multipliers Method
Similarly, adjust the monitor_new_multipliers method to align with the updated DOM structure:
python
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 getLatestMultipliers() {
// Navigate through the specified DOM structure
const historyContainer = document.querySelector('div.result-history.disabled-on-game-focused.my-2');
if (!historyContainer) return null;
const statsDropdown = historyContainer.querySelector('div.stats.dropdown');
if (!statsDropdown) return null;
const payoutsWrapper = statsDropdown.querySelector('div.payouts-wrapper');
if (!payoutsWrapper) return null;
const payoutsBlock = payoutsWrapper.querySelector('div.payouts-block');
if (!payoutsBlock) return null;
const multiplierElements = payoutsBlock.querySelectorAll('app-bubble-multiplier.payout.ng-star-enabled div.bubble-multiplier.font-weight-bold');
const multipliers = [];
multiplierElements.forEach(elem => {
// Extract the number after 'style =' if present
const styleText = elem.getAttribute('style') || '';
const match = styleText.match(/(\d+(\.\d+)?)/);
if (match) {
multipliers.push(parseFloat(match[1]));
} else {
// Fallback: Try to extract number from text content
const text = elem.textContent.trim().replace('x', '');
const num = parseFloat(text);
if (!isNaN(num)) {
multipliers.push(num);
}
}
});
return multipliers.length > 0 ? multipliers[multipliers.length - 1] : null;
}
return getLatestMultipliers();
"""
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
Explanation of Changes:
Consistent Selector Hierarchy: The method now follows the same DOM traversal to ensure consistency.
Latest Multiplier Extraction: It retrieves the latest (most recent) multiplier by selecting the last element in the multiplierElements list.
3. Handling Iframes (If Applicable)
Your current code attempts to switch to iframes, specifically those containing "spribegaming" in their src attribute. However, based on your DOM traversal steps, it seems that the multiplier elements are directly accessible without needing to switch to an iframe. Here's how to adjust this:
Verify If Iframes Are Necessary: Inspect the Aviator page to confirm whether the multiplier elements reside within an iframe. If they are directly in the main DOM, you can remove the iframe handling logic.
If Iframes Are Present and Necessary: Ensure that the selectors within the iframe match the DOM structure you've provided. Adjust the JavaScript accordingly.
Here's an adjusted version of the scrape method without iframe handling (assuming multipliers are in the main DOM):
python
def scrape(self):
try:
self.setup_driver()
self.login()
self.navigate_to_aviator()
time.sleep(5) # Ensure the page has fully loaded
# Directly extract multipliers from the main DOM
rounds_data = self.get_historical_multipliers()
print("Monitoring for new multipliers...")
new_data = self.monitor_new_multipliers(duration=60) # Reduced to 60 seconds
rounds_data.extend(new_data)
if not rounds_data:
print("No multipliers data collected.")
else:
filepath = self.save_data(rounds_data)
self.analyze_results(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()
Explanation of Changes:
Removed Iframe Handling: The scraper now directly accesses the main DOM without iterating through iframes.
Simplified Data Collection: It fetches historical multipliers and then monitors new ones sequentially.
Note: If multipliers are indeed within an iframe, you'll need to maintain the iframe switching logic and ensure that the selectors within the iframe match your specified DOM structure.
4. Additional Enhancements
Error Handling: Ensure that all possible exceptions are caught and handled gracefully. You've already implemented screenshots upon errors, which is excellent for debugging.
Dynamic Waiting: Instead of using fixed time.sleep calls, consider using Selenium's explicit waits to wait for specific elements to load. This makes your scraper more resilient to varying load times.
Headless Mode: If you're running this scraper on a server or don't need to see the browser, uncomment the headless option to run Chrome in headless mode:
python
options.add_argument('--headless')
5. Complete Revised Code
Here's the revised version of your AviatorScraper class with the aforementioned changes:
python
6. Testing and Validation
After implementing these changes:
Run Your Scraper: Execute the script in an environment where Selenium can control a browser (ensure you have the necessary drivers installed).
Monitor Outputs: Observe the console logs to ensure that multipliers are being detected and extracted correctly.
Check Saved Data: Verify the JSON files in the data directory to confirm that multipliers are stored as expected.
Handle Edge Cases: Ensure the scraper gracefully handles scenarios where the expected elements aren't found or the page structure changes.
7. Additional Tips
Dynamic Content Loading: If the Aviator game uses dynamic content loading (e.g., AJAX), you may need to wait for specific events or use more sophisticated methods to detect when new multipliers are available.
Respect Website Policies: Ensure that your scraping activities comply with Betika's terms of service and robots.txt guidelines. Excessive scraping can lead to IP blocking or other restrictions.
Error Handling Enhancements: Consider implementing retry mechanisms for transient errors and better logging for easier debugging.
By aligning your selectors with the provided DOM structure and refining your data extraction logic, your scraper should more accurately capture the multiplier values from the Aviator game on Betika. Test thoroughly and adjust as necessary based on the website's actual behavior and structure.
Not yet included in a published release.
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):
self.driver.get("https://betika.com/en-ke/aviator")
print("Navigated to Aviator page.")
# Wait until the result history section is present
try:
self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.result-history.disabled-on-game-focused.my-2")))
print("Result history section loaded.")
except TimeoutException:
print("Result history section did not load in time.")
self.driver.save_screenshot(os.path.join(self.SCREENSHOT_DIR, "aviator_page_timeout.png"))
raise
def get_historical_multipliers(self):
try:
js_script = """
function extractMultipliers() {
const historyContainer = document.querySelector('div.result-history.disabled-on-game-focused.my-2');
if (!historyContainer) return [];
const statsDropdown = historyContainer.querySelector('div.stats.dropdown');
if (!statsDropdown) return [];
const payoutsWrapper = statsDropdown.querySelector('div.payouts-wrapper');
if (!payoutsWrapper) return [];
const payoutsBlock = payoutsWrapper.querySelector('div.payouts-block');
if (!payoutsBlock) return [];
const multiplierElements = payoutsBlock.querySelectorAll('app-bubble-multiplier.payout.ng-star-enabled div.bubble-multiplier.font-weight-bold');
const multipliers = [];
multiplierElements.forEach(elem => {
const styleText = elem.getAttribute('style') || '';
const match = styleText.match(/(\d+(\.\d+)?)/);
if (match) {
multipliers.push(parseFloat(match[1]));
} else {
const text = elem.textContent.trim().replace('x', '');
const num = parseFloat(text);
if (!isNaN(num)) {
multipliers.push(num);
}
}
});
return multipliers.map(multiplier => ({
multiplier: multiplier,
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):
start_time = time.time()
new_multipliers = []
last_multiplier = None
while time.time() - start_time < duration:
try:
js_script = """
function getLatestMultipliers() {
const historyContainer = document.querySelector('div.result-history.disabled-on-game-focused.my-2');
if (!historyContainer) return null;
const statsDropdown = historyContainer.querySelector('div.stats.dropdown');
if (!statsDropdown) return null;
const payoutsWrapper = statsDropdown.querySelector('div.payouts-wrapper');
if (!payoutsWrapper) return null;
const payoutsBlock = payoutsWrapper.querySelector('div.payouts-block');
if (!payoutsBlock) return null;
const multiplierElements = payoutsBlock.querySelectorAll('app-bubble-multiplier.payout.ng-star-enabled div.bubble-multiplier.font-weight-bold');
const multipliers = [];
multiplierElements.forEach(elem => {
const styleText = elem.getAttribute('style') || '';
const match = styleText.match(/(\d+(\.\d+)?)/);
if (match) {
multipliers.push(parseFloat(match[1]));
} else {
const text = elem.textContent.trim().replace('x', '');
const num = parseFloat(text);
if (!isNaN(num)) {
multipliers.push(num);
}
}
});
return multipliers.length > 0 ? multipliers[multipliers.length - 1] : null;
}
return getLatestMultipliers();
"""
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 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()
# Directly extract multipliers from the main DOM
rounds_data = self.get_historical_multipliers()
print("Monitoring for new multipliers...")
new_data = self.monitor_new_multipliers(duration=60) # Reduced to 60 seconds
rounds_data.extend(new_data)
if not rounds_data:
print("No multipliers data collected.")
else:
filepath = self.save_data(rounds_data)
self.analyze_results(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):
# Parse multipliers to floats
multipliers = []
for round_data in rounds_data:
multiplier = round_data.get('multiplier')
if isinstance(multiplier, (int, float)):
multipliers.append(multiplier)
else:
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()