It looks like you're encountering issues when trying to extract multipliers from the Betika Aviator page using Selenium. The errors you're seeing indicate that the script is unable to locate the desired elements within the main context and any of the iframes present on the page. Let's break down the potential causes and provide solutions to address them.
Possible Causes
- Incorrect CSS Selectors: The CSS selectors used in your script might have changed due to updates in the website's structure.
- Dynamic Content Loading: The multipliers might be loaded dynamically after your script attempts to access them.
- Shadow DOM Usage: The elements might be encapsulated within a Shadow DOM, making them inaccessible via standard Selenium methods.
- Cross-Domain Iframes: Some iframes might be cross-domain, preventing Selenium from accessing their content due to security restrictions.
- Anti-Scraping Measures: The website might have implemented measures to prevent automated scraping, causing unexpected behaviors.
Solutions and Recommendations
-
Verify and Update CSS Selectors
- Action: Manually inspect the Betika Aviator page using your browser's Developer Tools to ensure that the CSS selectors in your script match the current structure of the page.
- How: Right-click on the element you want to scrape (the multiplier) and select "Inspect". Update your selectors accordingly.
-
Increase Wait Times and Use Explicit Waits
- Action: Ensure that elements have fully loaded before your script attempts to interact with them.
- How: You can increase the wait time and add more explicit waits for specific elements.
-
Handle Shadow DOM Elements
- Action: If the elements are within a Shadow DOM, standard Selenium methods won't work. You'll need to use JavaScript to pierce through the Shadow DOM.
- How: Use JavaScript execution to access Shadow DOM elements.
-
Handle Cross-Domain Iframes
- Action: Selenium cannot access iframes that are loaded from a different domain due to the Same-Origin Policy.
- Workaround: Focus on the main context or identify if the required elements are within same-origin iframes.
-
Implement Enhanced Error Handling and Logging
- Action: Improve your error handling to capture more detailed information. This will help in diagnosing issues more effectively.
-
Consider Using Network Interception or API Calls
- Action: Sometimes, data is fetched via API calls which can be intercepted. Using tools like Selenium Wire or directly accessing the APIs can be more reliable.
-
Respect Website’s Terms of Service
Revised Code with Enhanced Logging and Error Handling
Below is an improved version of your script with enhanced logging, updated error handling, and suggestions to address the potential issues mentioned above.
import os
import time
import traceback
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,
NoSuchElementException,
NoSuchFrameException,
StaleElementReferenceException
)
from webdriver_manager.chrome import ChromeDriverManager
def scrape_aviator_history():
driver = None
multipliers = []
SCREENSHOT_DIR = "screenshots"
if not os.path.exists(SCREENSHOT_DIR):
os.makedirs(SCREENSHOT_DIR)
options = webdriver.ChromeOptions()
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--window-size=1920,1080')
# Optional: Run in headless mode
# options.add_argument('--headless')
try:
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
wait = WebDriverWait(driver, 30) # Increased wait time
# Login process
driver.get("https://betika.com/en-ke/login")
print("Opened Betika login page.")
try:
# Adjusted selector in case it has changed
close_modal_button = 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.")
try:
phone_input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "input.input[type='tel'], input[name='phone']")))
phone_input.clear()
phone_input.send_keys("0703972766")
print("Entered phone number.")
except TimeoutException:
print("Phone input field not found.")
return []
try:
password_input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "input.input[type='password'], input[name='password']")))
password_input.clear()
password_input.send_keys("ComplexPass123!")
print("Entered password.")
except TimeoutException:
print("Password input field not found.")
return []
try:
login_button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.session__form__button.login.button.button__secondary")))
login_button.click()
print("Clicked login button.")
except TimeoutException:
print("Login button not found or not clickable.")
return []
# Wait for login to complete
time.sleep(5) # Consider replacing with a wait for a specific element post-login
# Navigate to Aviator page
driver.get("https://betika.com/en-ke/aviator")
print("Navigated to Aviator page.")
time.sleep(10) # Adjusted wait time; consider using explicit waits
# Save screenshot to verify page load
aviator_screenshot = os.path.join(SCREENSHOT_DIR, "aviator_page.png")
driver.save_screenshot(aviator_screenshot)
print(f"Saved screenshot of Aviator page at {aviator_screenshot}")
# Update iframe handling
iframes = driver.find_elements(By.TAG_NAME, "iframe")
print(f"Found {len(iframes)} iframes on the page.")
def extract_multipliers_from_context(current_driver):
try:
# Update selector based on actual page structure
history_container = wait.until(EC.presence_of_element_located(
(By.CSS_SELECTOR, "div.result-history.disabled-on-game-focused.my-2")))
print("Found history container.")
# Navigate through the DOM structure
try:
stats_dropdown = history_container.find_element(By.CSS_SELECTOR, "div.stats.dropdown")
payouts_wrapper = stats_dropdown.find_element(By.CSS_SELECTOR, "div.payouts-wrapper")
payouts_block = payouts_wrapper.find_element(By.CSS_SELECTOR, "div.payouts-block")
except NoSuchElementException:
print("One of the nested elements was not found.")
return []
multiplier_elements = payouts_block.find_elements(
By.CSS_SELECTOR, "app-bubble-multiplier.payout.ng-star-enabled")
print(f"Found {len(multiplier_elements)} multiplier elements.")
local_multipliers = []
for element in multiplier_elements:
try:
bubble_div = element.find_element(
By.CSS_SELECTOR, "div.bubble-multiplier.font-weight-bold")
# Get the style attribute
style_attr = bubble_div.get_attribute("style")
print(f"Style attribute: {style_attr}")
# Extract the multiplier from the div's text
multiplier_text = bubble_div.text.strip()
if multiplier_text:
local_multipliers.append(multiplier_text)
print(f"Extracted multiplier: {multiplier_text}")
except NoSuchElementException:
print("Bubble multiplier div not found in an element.")
except StaleElementReferenceException:
print("Stale element reference when accessing bubble multiplier.")
except Exception as e:
print(f"Unexpected error extracting multiplier: {e}")
return local_multipliers
except TimeoutException:
print("History container not found in this context.")
return []
except Exception as e:
print(f"Error in extract_multipliers_from_context: {e}")
traceback.print_exc()
return []
# Try in main context first
main_multipliers = extract_multipliers_from_context(driver)
if main_multipliers:
multipliers.extend(main_multipliers)
print("Found multipliers in main context.")
else:
print("No multipliers found in main context, trying iframes...")
# If no multipliers found in main context, try iframes
if not multipliers:
for index, iframe in enumerate(iframes):
try:
driver.switch_to.frame(iframe)
print(f"Switched to iframe {index}")
# Save screenshot of iframe
iframe_screenshot = os.path.join(SCREENSHOT_DIR, f"iframe_{index}.png")
driver.save_screenshot(iframe_screenshot)
print(f"Saved screenshot of iframe {index} at {iframe_screenshot}")
iframe_multipliers = extract_multipliers_from_context(driver)
if iframe_multipliers:
multipliers.extend(iframe_multipliers)
print(f"Found multipliers in iframe {index}")
driver.switch_to.default_content()
break # Exit after finding the multipliers
else:
print(f"No multipliers found in iframe {index}")
except NoSuchFrameException:
print(f"Iframe {index} does not exist.")
except Exception as e:
print(f"Error processing iframe {index}: {e}")
traceback.print_exc()
finally:
driver.switch_to.default_content()
if not multipliers:
print("No multipliers found in any context.")
except Exception as e:
print(f"An error occurred during scraping: {e}")
traceback.print_exc()
if driver:
error_screenshot = os.path.join(SCREENSHOT_DIR, "error_screenshot.png")
driver.save_screenshot(error_screenshot)
print(f"Saved error screenshot at {error_screenshot}")
finally:
if driver:
driver.quit()
print("Closed the WebDriver.")
return multipliers
def main():
try:
multipliers = scrape_aviator_history()
if multipliers:
print(f"\nFound {len(multipliers)} multipliers:")
for idx, multiplier in enumerate(multipliers, start=1):
print(f"{idx}: {multiplier}")
else:
print("\nNo multipliers found or scraping failed.")
except Exception as e:
print(f"\nAn unexpected error occurred in main: {e}")
traceback.print_exc()
if __name__ == "__main__":
main()
Key Improvements and Additions
-
Enhanced Error Logging:
- Added
traceback.print_exc() to print detailed stack traces when exceptions occur.
- More specific exception handling to identify where and why failures happen.
-
Updated CSS Selectors:
- Included alternative selectors for phone and password inputs to account for possible changes in the website's structure.
-
Increased Wait Times:
- Increased the
WebDriverWait timeout to 30 seconds to accommodate slower page loads.
- Adjusted
time.sleep durations; consider replacing them with explicit waits for more reliability.
-
Screenshot Capture:
- Saved screenshots of the Aviator page and each iframe to help with debugging and verifying if elements are present.
-
Handling Stale Elements:
- Added handling for
StaleElementReferenceException which can occur if the DOM changes while interacting with elements.
-
Comments and Recommendations:
- Provided comments within the code to guide further adjustments and considerations.
Next Steps
-
Verify Screenshots:
- Check the
screenshots directory to see the captured images. This will help you understand whether the page and iframes are loading correctly and whether the desired elements are present.
-
Adjust Selectors as Needed:
- Based on the screenshots, update the CSS selectors to match the current structure of the Betika Aviator page.
-
Consider Using JavaScript for Dynamic Content:
- If the multipliers are rendered using JavaScript frameworks or within Shadow DOMs, you might need to execute JavaScript to extract the data.
-
Explore API Alternatives:
- Inspect network requests when loading the Aviator page to see if there's an API you can directly interact with to retrieve the multipliers, which can be more efficient and reliable than scraping.
-
Respect Website Policies:
- Ensure that your scraping activities comply with Betika's terms and policies to avoid potential legal issues or being blocked.
-
Monitor for Anti-Bot Measures:
- Be aware that websites may implement measures to detect and prevent automated scraping. If you suspect this is the case, you may need to implement measures to mimic human interactions more closely, such as randomized delays and user-agent rotations.
Final Thoughts
Web scraping can be challenging, especially with dynamic websites that frequently update their structures or implement anti-scraping measures. Continuous monitoring and updating of your scraping scripts are essential to maintain their effectiveness. Additionally, always ensure that your activities are ethical and comply with the website's terms of service.
If you continue to face issues after implementing these changes, consider providing additional details such as screenshots or specific observations from the capturized images. This will enable more targeted assistance.