It appears that your scraper is consistently capturing incorrect multiplier values (2881.31x and 453.94x) instead of the actual multipliers displayed on the Betika Aviator page. This issue can stem from several factors, such as incorrect element selectors, dynamic content loading, or even how the multipliers are rendered on the page.
Let's walk through potential reasons for this discrepancy and provide actionable solutions to help you accurately scrape the correct multiplier values.
1. Inspect the Iframe's Content Structure
Before delving into code modifications, it's essential to understand how the multipliers are rendered within the iframe. Here's what you should do:
a. Manual Inspection with Developer Tools
-
Open the Aviator Page Manually:
- Navigate to
https://betika.com/en-ke/aviator using your browser.
-
Locate the Relevant Iframe:
- Right-click on the Aviator game area and select Inspect (Chrome) or Inspect Element (Firefox).
- In the Elements panel, locate the iframe that contains the Aviator game. It should have a
src attribute containing "spribegaming".
-
Examine How Multipliers Are Displayed:
- Text Elements: Check if the multipliers are present as text within standard HTML elements (e.g.,
<div>, <span>).
- Canvas or SVG: If the multipliers are rendered using
<canvas> or <svg>, scraping text directly won't work.
- Web Fonts or Obfuscated Elements: If the text is rendered using web fonts or obfuscated methods, standard text scraping might fail.
b. Determine Rendering Method
2. Adjust Your Scraping Strategy Based on Findings
a. If Multipliers Are Text-Based
Ensure that your scraper targets the correct elements containing the multipliers.
Steps to Update Your Scraper:
-
Update JavaScript Selector:
Modify the JavaScript used in the analyze_iframe method to accurately select the elements containing multiplier values.
js_script = """
return Array.from(document.querySelectorAll('.multiplier-selector')) // Update this selector
.map(el => ({
multiplier: el.textContent.trim(),
timestamp: new Date().toISOString()
}));
"""
- Action: Replace
'.multiplier-selector' with the actual CSS selector identified during manual inspection.
-
Enhance Selector Specificity:
Ensure that your selector uniquely targets multiplier elements to avoid capturing irrelevant data.
js_script = """
return Array.from(document.querySelectorAll('.specific-class-for-multiplier'))
.map(el => ({
multiplier: el.textContent.trim(),
timestamp: new Date().toISOString()
}));
"""
-
Handle Dynamic Content Loading:
If multipliers are loaded dynamically (e.g., via AJAX), ensure that your scraper captures updates in real-time.
- Possible Solution: Increase the frequency of data extraction or use mutation observers within the iframe to detect changes.
b. If Multipliers Are Rendered via Canvas or Graphics
Scraping directly becomes challenging. Consider alternative approaches:
-
Intercept Network Traffic:
- Use browser developer tools or tools like Wireshark to monitor network requests from the iframe.
- Look for API endpoints or WebSocket communications that transmit multiplier data.
- Modify your scraper to access these endpoints directly, bypassing the need for DOM scraping.
-
Use OCR for Canvas Elements:
- Capture screenshots of the iframe at regular intervals.
- Apply Optical Character Recognition (OCR) techniques (e.g., using Tesseract) to extract multiplier values from the images.
Example Integration with OCR:
from PIL import Image
import pytesseract
def capture_multiplier_image(self, iframe_element):
location = iframe_element.location
size = iframe_element.size
screenshot_path = os.path.join(self.SCREENSHOT_DIR, "iframe_screenshot.png")
self.driver.save_screenshot(screenshot_path)
image = Image.open(screenshot_path)
multiplier_region = image.crop((
location['x'],
location['y'],
location['x'] + size['width'],
location['y'] + size['height']
))
multiplier_image_path = os.path.join(self.SCREENSHOT_DIR, "multiplier.png")
multiplier_region.save(multiplier_image_path)
multiplier_text = pytesseract.image_to_string(multiplier_image_path)
return multiplier_text.strip()
- Caveat: OCR can be error-prone and may require preprocessing steps to improve accuracy.
c. Verify Correct Iframe Selection
Ensure you're interacting with the correct iframe that contains the game multipliers.
Steps:
-
Log Iframe src Attributes:
for index, iframe in enumerate(iframes):
iframe_src = iframe.get_attribute("src")
print(f"Iframe {index} src: {iframe_src}")
-
Confirm the Correct Iframe:
- Based on the
src attribute, ensure you're selecting the iframe that truly contains the multiplier data.
-
Switch to the Correct Iframe:
- Modify the condition if necessary to target the correct iframe.
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)
#...
3. Enhance Scraper Robustness and Accuracy
To improve the reliability of your scraper, consider the following enhancements:
a. Implement Logging with Timestamps
Add more detailed logging to track scraping progress and identify where issues may occur.
import logging
# Configure logging at the beginning of your script
logging.basicConfig(
filename='aviator_scraper.log',
level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(message)s'
)
# Replace print statements with logging
logging.info("Opened Betika login page.")
logging.info("No modal to close.")
# ... and so on
b. Handle Dynamic Selectors and Frames
Websites often change their structure, which can break scrapers. Implement dynamic selectors or fallback strategies.
# Example: Try multiple selectors for multipliers
js_script = """
const selectors = ['.multiplier-class1', '.multiplier-class2', '#multiplier-id'];
for (let selector of selectors) {
let elements = document.querySelectorAll(selector);
if (elements.length > 0) {
return Array.from(elements).map(el => ({
multiplier: el.textContent.trim(),
timestamp: new Date().toISOString()
}));
}
}
return [];
"""
c. Implement Error Handling and Retries
Enhance your scraper to handle intermittent failures gracefully.
import retrying
@retrying.retry(stop_max_attempt_number=3, wait_fixed=2000)
def find_element_with_retry(selector):
return self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, selector)))
# Use the above function in your scraping steps
4. Alternative Approach: Utilize APIs or WebSocket Connections
If possible, interacting directly with the game's backend APIs or WebSocket connections can provide real-time multiplier data without relying on DOM scraping. Here's how you can approach this:
a. Identify Network Endpoints
-
Use Browser Developer Tools:
- Open the Network tab.
- Filter by WebSockets or XHR to identify data streams.
-
Locate Relevant Data Streams:
- Observe which requests contain multiplier data.
- Note the request URLs and data formats.
b. Replicate Requests Programmatically
Once you've identified the relevant endpoints:
-
Analyze Request Requirements:
- Check for required headers, authentication tokens, or parameters.
-
Use Python's requests or websocket Libraries:
-
For REST APIs:
import requests
headers = {
'Authorization': 'Bearer YOUR_TOKEN',
# Add other necessary headers
}
response = requests.get('https://api.betika.com/aviator/multipliers', headers=headers)
multipliers = response.json()
-
For WebSockets:
import websocket
import json
def on_message(ws, message):
data = json.loads(message)
print(f"Multiplier: {data['multiplier']}x")
ws = websocket.WebSocketApp(
"wss://betika.com/aviator/socket",
on_message=on_message
)
ws.run_forever()
-
Note: Replace the URLs and parameters with actual values identified during inspection.
c. Advantages of Using APIs/WebSockets
- Efficiency: Direct access to data without rendering overhead.
- Accuracy: Reduced risk of missing or misinterpreting data.
- Real-Time Access: Immediate updates as data is pushed from the server.
d. Caveats
- Authentication: May require handling tokens or session data.
- Legal Considerations: Ensure that accessing APIs directly complies with the website's terms of service.
- Obfuscation: Some sites may secure their APIs, making direct access challenging.
5. Example Revised Scraper Code
Assuming that upon inspection, multipliers are present as text within specific HTML elements, here's an updated version of your AviatorScraper class with enhanced selector targeting and logging:
import os
import time
import json
import logging
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
# Configure logging
logging.basicConfig(
filename='aviator_scraper.log',
level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(message)s'
)
class AviatorScraper:
def __init__(self):
self.SCREENSHOT_DIR = "screenshots"
self.DATA_DIR = "data"
self.MAX_WAIT = 30
self.multipliers = []
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')
# Optional: Run headless
# options.add_argument('--headless')
self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
self.wait = WebDriverWait(self.driver, self.MAX_WAIT)
logging.info("WebDriver initialized.")
def login(self):
self.driver.get("https://betika.com/en-ke/login")
logging.info("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()
logging.info("Closed modal.")
except TimeoutException:
logging.info("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)
logging.info(step['message'])
except TimeoutException:
logging.error(f"Timeout while trying to {step['message']}.")
raise
def navigate_to_aviator(self):
time.sleep(5) # Consider replacing with explicit waits
self.driver.get("https://betika.com/en-ke/aviator")
logging.info("Navigated to Aviator page.")
time.sleep(10) # Ensure page loads completely
def analyze_iframe(self, iframe_element):
try:
self.driver.switch_to.frame(iframe_element)
logging.info("Switched to game iframe.")
# Adjust the selector based on actual DOM structure
# Example: Assume multipliers are within elements with class 'multiplier-value'
js_script = """
return Array.from(document.querySelectorAll('.multiplier-value'))
.map(el => ({
multiplier: el.textContent.trim(),
timestamp: new Date().toISOString()
}));
"""
rounds_data = []
start_time = time.time()
observation_time = 300 # 5 minutes
while time.time() - start_time < observation_time:
try:
new_multipliers = self.driver.execute_script(js_script)
if new_multipliers:
for multiplier in new_multipliers:
if multiplier not in rounds_data:
rounds_data.append(multiplier)
logging.info(f"Found new multiplier: {multiplier['multiplier']}")
time.sleep(5) # Wait before next check
except JavascriptException as je:
logging.error(f"JavaScript error: {je}")
continue
return rounds_data
finally:
self.driver.switch_to.default_content()
logging.info("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)
logging.info(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")
logging.info(f"Found {len(iframes)} iframes on the page.")
all_rounds_data = []
for index, iframe in enumerate(iframes):
iframe_src = iframe.get_attribute("src")
logging.info(f"Iframe {index} src: {iframe_src}")
if "spribegaming" in iframe_src.lower():
logging.info(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:
logging.warning("No multipliers found during observation period.")
except Exception as e:
logging.error(f"An error occurred during scraping: {e}")
if self.driver:
screenshot_path = os.path.join(self.SCREENSHOT_DIR, "error_screenshot.png")
self.driver.save_screenshot(screenshot_path)
logging.info(f"Saved error screenshot to {screenshot_path}")
finally:
if self.driver:
self.driver.quit()
logging.info("WebDriver closed.")
@staticmethod
def analyze_results(rounds_data, filepath):
multipliers = []
for round_data in rounds_data:
try:
multiplier = float(round_data['multiplier'].rstrip('x'))
multipliers.append(multiplier)
except ValueError:
logging.warning(f"Invalid multiplier format: {round_data['multiplier']}")
if multipliers:
avg_multiplier = sum(multipliers) / len(multipliers)
max_multiplier = max(multipliers)
min_multiplier = min(multipliers)
analysis = {
"Total rounds recorded": len(multipliers),
"Average multiplier": f"{avg_multiplier:.2f}x",
"Highest multiplier": f"{max_multiplier:.2f}x",
"Lowest multiplier": f"{min_multiplier:.2f}x",
"Data saved to": filepath
}
print("\nResults Analysis:")
for key, value in analysis.items():
print(f"{key}: {value}")
logging.info("Results Analysis:")
for key, value in analysis.items():
logging.info(f"{key}: {value}")
else:
logging.warning("No valid multipliers to analyze.")
def main():
scraper = AviatorScraper()
scraper.scrape()
if __name__ == "__main__":
main()
Key Enhancements in the Revised Code:
-
Detailed Logging: Replaced print statements with structured logging to aviator_scraper.log for better traceability.
-
Dynamic Selector Placeholder: Updated js_script with a placeholder selector ('.multiplier-value'). You must replace this with the actual selector found during manual inspection.
-
Duplicate Checks: Prevents recording the same multiplier multiple times by checking if it's already in rounds_data.
-
Error Handling Enhancements: Added warnings and error logs for invalid multiplier formats and other potential issues.
-
Modular Code Structure: Maintains clear separation of concerns, making future adjustments easier.
6. Final Recommendations
-
Manual Verification:
- Before running the scraper, manually verify the exact CSS selectors for the multiplier elements within the iframe.
- Use unique identifiers or classes to precisely target these elements.
-
Stay Updated with Site Changes:
- Websites frequently update their layouts and structures, which can break scrapers. Regularly review and update your scraper accordingly.
-
Respect Website's Terms of Service:
- Ensure that your scraping activities comply with Betika's Terms of Service to avoid potential legal issues.
-
Optimize Scraper Performance:
- Consider reducing the observation period if possible.
- Implement asynchronous scraping if real-time data capture is required.
-
Handle Anti-Bot Measures:
- Some websites employ anti-scraping measures like CAPTCHAs, IP blocking, or dynamic content rendering. Be prepared to handle or work around these if encountered.
-
Explore Alternative Data Sources:
- If scraping proves too unreliable, consider reaching out to Betika for official APIs or data sharing options, especially if the data is intended for legitimate use.
By following these steps and carefully adjusting your scraper based on the actual content structure of the Aviator game page, you should be able to capture the correct multiplier values accurately.
If you continue to face challenges, please provide additional details about how the multipliers are rendered on the page (e.g., screenshots, specific HTML structures), and I can offer more targeted assistance.