It looks like your script is currently unable to locate any historical multipliers on the Betika Aviator page. This can be due to several reasons, such as changes in the website's structure, incorrect CSS selectors, or issues with the iframe handling. Additionally, you've requested to reduce the monitoring duration from 300 seconds (5 minutes) to 60 seconds (1 minute).
Here's how you can address these issues:
-
Update CSS Selectors:
The selectors used in your script might no longer match the current structure of the Betika Aviator page. It's crucial to inspect the webpage to confirm the current selectors.
-
Reduce Monitoring Duration:
Adjust the duration parameter in the monitor_new_multipliers method from 300 to 60 seconds.
-
Enhance Debugging:
Add more logging and screenshots to help identify where the script might be failing.
-
Handle Dynamic Content:
Ensure that the script waits appropriately for dynamic content to load within the iframe.
Below is the revised version of your script with these considerations:
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()
Key Changes and Enhancements:
-
Reduced Monitoring Duration:
- Changed the
duration parameter in the monitor_new_multipliers method from 300 to 60 seconds.
def monitor_new_multipliers(self, duration=60): # Reduced duration to 60 seconds
-
Enhanced Error Handling and Debugging:
- Added
try-except blocks around critical sections to catch exceptions and take screenshots for debugging.
- Screenshots are saved in the
screenshots directory with descriptive filenames to help identify where issues occur.
-
Verification of CSS Selectors:
- Ensure that the CSS selectors used (
.last-results .last-results-item) accurately reflect the current structure of the Betika Aviator page. If the website has updated its class names or element hierarchy, you'll need to update these selectors accordingly.
- Action: Use your browser's developer tools (right-click on the element and select "Inspect") to verify the current classes and structure. Update the selectors in the JavaScript snippets within the
get_historical_multipliers and monitor_new_multipliers methods if necessary.
-
Wait for Elements to Load:
- Added a wait condition before attempting to extract multipliers inside the iframe to ensure that the elements are present.
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 []
-
Logging Current iframe Source:
- Printed the
src attribute of the iframe being analyzed to ensure the correct iframe is being targeted.
-
Data Parsing Improvements:
- The
analyze_results method now includes error handling for parsing the multipliers. It skips invalid formats and logs them for review.
-
Optional Headless Mode:
- If you prefer the browser not to open a visible window during scraping, uncomment the headless option.
Next Steps:
-
Verify and Update CSS Selectors:
- Inspect the Betika Aviator page to ensure that
.last-results .last-results-item correctly selects the multiplier elements. If not, update these selectors to match the current HTML structure.
-
Run the Script and Review Screenshots:
- Execute the script and monitor the console output along with the
screenshots directory. If the script fails to find elements, the screenshots will provide visual context for debugging.
-
Adjust Sleep Durations if Necessary:
- Depending on the page load times and dynamic content loading, you might need to adjust the
time.sleep durations in the navigate_to_aviator method.
-
Handle Multiple Iframes if Applicable:
- If there are multiple relevant iframes, ensure that the script processes each one correctly. Currently, it processes all iframes containing "spribegaming" in their
src.
-
Respect Website's Terms of Service:
- Ensure that your scraping activities comply with Betika's terms of service to avoid any potential legal issues or IP blocking.
-
Consider Headless Execution for Automation:
- For running the script in environments without a GUI or for deploying it as a scheduled task, enabling headless mode can be beneficial.
Example Output After Changes:
After implementing these changes and ensuring that the CSS selectors are correct, you should see output similar to the following (assuming the script successfully finds multipliers):
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 with src: https://example.com/spribegaming
Switched to iframe.
Multiplier elements found inside iframe.
Found 10 historical multipliers
Monitoring for new multipliers...
New multiplier detected: 2.5x
New multiplier detected: 3.0x
...
Switched back to default content.
Saved data to data/aviator_data_20240427_143500.json
Results Analysis:
Total multipliers recorded: 12
Historical multipliers: 10
New multipliers captured: 2
Average multiplier: 2.75x
Highest multiplier: 3.00x
Lowest multiplier: 2.50x
Data saved to: data/aviator_data_20240427_143500.json
Troubleshooting Tips:
-
No Multipliers Found:
- Check Selectors: Re-inspect the website to ensure selectors match.
- Delayed Loading: Increase
time.sleep durations or use more explicit waits.
- Iframe Issues: Ensure that the multipliers are indeed within the targeted iframe.
-
JavaScript Errors:
- Review the screenshots saved in the
screenshots directory to identify issues with the JavaScript execution.
- Ensure that the JavaScript code accurately reflects the current DOM structure.
-
Authentication Issues:
- If the login isn't successful, verify the login flow and update selectors or steps as needed.
- Check if there are additional authentication steps like CAPTCHA or two-factor authentication.
By implementing these changes and following the troubleshooting steps, you should be able to successfully scrape the historical and new multipliers from the Betika Aviator page within a reduced monitoring duration of 60 seconds.