My updated code:
However, it was unable to login. It did not put any details in phone or password.
Error:
Opened Betika login page
An error occurred during scraping: Message:
Stacktrace:
GetHandleVerifier [0x00977143+25587]
(No symbol) [0x0090A2E4]
(No symbol) [0x00802113]
(No symbol) [0x00846F62]
(No symbol) [0x008471AB]
(No symbol) [0x00887852]
(No symbol) [0x0086ABE4]
(No symbol) [0x00885370]
(No symbol) [0x0086A936]
(No symbol) [0x0083BA73]
(No symbol) [0x0083C4CD]
GetHandleVerifier [0x00C54C63+3030803]
GetHandleVerifier [0x00CA6B99+3366473]
GetHandleVerifier [0x00A095F2+624802]
GetHandleVerifier [0x00A10E6C+655644]
(No symbol) [0x00912C9D]
(No symbol) [0x0090FD68]
(No symbol) [0x0090FF05]
(No symbol) [0x00902336]
BaseThreadInitThunk [0x74EF7BA9+25]
RtlInitializeExceptionChain [0x771EC11B+107]
RtlClearBits [0x771EC09F+191]
An error occurred: object of type 'NoneType' has no len()
The code itself:
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.webdriver.common.action_chains import ActionChains
from webdriver_manager.chrome import ChromeDriverManager
import time
Function to scrape aviator history after logging in
def scrape_aviator_history():
# Set Chrome options (without headless mode)
options = webdriver.ChromeOptions()
# options.add_argument('--headless') # Comment out this line to see the browser
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--disable-gpu')
code
Assistant
# Initialize WebDriver with ChromeDriverManager
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
try:
# Step 1: Open Betika login page
driver.get("https://betika.com/en-ke/login")
print("Opened Betika login page")
# Step 2: Ensure elements are present
wait = WebDriverWait(driver, 20)
# Check for phone input
phone_input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "input#login-phone")))
print("Phone input found.")
# Check for password input
password_input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "input#login-password")))
print("Password input found.")
# Step 3: Use JavaScript to set phone number
driver.execute_script("arguments[0].value = '';", phone_input) # Clear any existing text
driver.execute_script("arguments[0].value = '0703972766';", phone_input) # Set phone number
print("Phone number entered.")
# Step 4: Use JavaScript to set password
driver.execute_script("arguments[0].value = '';", password_input) # Clear any existing text
driver.execute_script("arguments[0].value = 'ComplexPass123!';", password_input) # Set password
print("Password entered.")
# Step 5: Click login button
login_button = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "button[type='submit']")))
print("Login button found.")
login_button.click()
print("Clicked login button.")
# Step 6: Wait for login to process (adjust this condition as needed)
time.sleep(5) # You may need to wait for the page to redirect after login
# Step 7: Now navigate to Aviator page after login
driver.get("https://betika.com/en-ke/aviator")
print("Navigated to Aviator page.")
# Step 8: Wait for the game-play div to appear
game_play = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.game-play")))
print("Game-play div found.")
# Step 9: Navigate to the history div
history_container = game_play.find_element(By.CSS_SELECTOR, "div.result-history.disabled-on-game-focused.my-2")
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")
# Step 10: Find all bubble multiplier elements
multiplier_elements = payouts_block.find_elements(By.CSS_SELECTOR, "app-bubble-multiplier.payout.ng-star-enabled")
# Step 11: Collect the multiplier values
multipliers = []
for element in multiplier_elements:
try:
# Find the inner div with the multiplier value
bubble_div = element.find_element(By.CSS_SELECTOR, "div.bubble-multiplier.font-weight-bold")
# Extract the multiplier text
multiplier = bubble_div.text
multipliers.append(multiplier)
except Exception as e:
print(f"Error processing element: {e}")
continue
return multipliers
except Exception as e:
print(f"An error occurred during scraping: {e}")
finally:
# Always quit the driver
driver.quit()
It looks like your Selenium script is encountering issues while attempting to log in to the Betika website. Specifically, the phone number and password fields are not being populated, leading to subsequent errors. Let's walk through potential causes and solutions to resolve this problem.
1. Verify Element Selectors
Issue: The CSS selectors input#login-phone and input#login-password might not correctly identify the phone and password input fields on the Betika login page. Websites often undergo updates that can change element IDs or structures.
Solution:
Inspect the Webpage: Use your browser’s developer tools (right-click on the page and select "Inspect") to verify the current IDs or selectors for the phone and password input fields.
Update Selectors if Necessary: If the IDs have changed, update your selectors accordingly.
Example:
python
# Example: If the phone input has changed to 'phone-number'
phone_input = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "input#phone-number")))
2. Use send_keys Instead of execute_script
Issue: Using JavaScript to set the value of input fields (execute_script) might not trigger the necessary events that the website relies on for input validation and form submission.
Solution: Use Selenium's send_keys method to input text into fields. This approach simulates real user input more accurately and ensures that all associated events are fired.
Updated Code Snippet:
python
# Step 3: Enter phone number using send_keys
phone_input.clear() # Clear any existing text
phone_input.send_keys('0703972766')
print("Phone number entered.")
# Step 4: Enter password using send_keys
password_input.clear() # Clear any existing text
password_input.send_keys('ComplexPass123!')
print("Password entered.")
3. Ensure Elements are Interactable
Issue: Sometimes, elements might be present in the DOM but not yet interactable (e.g., not visible or enabled).
Solution: Use EC.element_to_be_clickable in your WebDriverWait to ensure that elements are ready for interaction.
Updated Code Snippet:
python
# Wait until phone input is clickable
phone_input = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#login-phone")))
print("Phone input is clickable.")
# Similarly for password input
password_input = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#login-password")))
print("Password input is clickable.")
4. Handle Potential Pop-ups or Modals
Issue: Sometimes, login pages may have pop-ups, modals, or overlays that obscure input fields, preventing interaction.
Solution: Detect and close any such obstructive elements before performing login actions.
Example:
python
try:
# Example: Close a modal if it exists
close_modal = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.close-modal")))
close_modal.click()
print("Closed modal.")
except:
print("No modal to close.")
5. Implement Enhanced Error Handling and Logging
Issue: The error object of type 'NoneType' has no len() suggests that the scrape_aviator_history function is returning None, likely because an exception occurred before it could return the multipliers list.
Solution:
Add Detailed Logging: Insert print statements or use Python’s logging module to trace the execution flow.
Handle Exceptions Gracefully: Ensure that the function returns an empty list or a meaningful value even when exceptions occur.
Updated Code Snippet:
python
def scrape_aviator_history():
# ... [initial setup code remains unchanged]
try:
# ... [login steps]
# Ensure login was successful by checking for a specific element post-login
profile_icon = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "selector-for-profile-icon")))
print("Login successful.")
# Navigate to Aviator page
driver.get("https://betika.com/en-ke/aviator")
print("Navigated to Aviator page.")
# ... [rest of scraping code]
return multipliers
except Exception as e:
print(f"An error occurred during scraping: {e}")
return [] # Return an empty list instead of None
finally:
driver.quit()
6. Add Explicit Waits Instead of time.sleep
Issue: Relying on fixed sleep durations (time.sleep(5)) can lead to unreliable behavior, especially if the page takes longer to load.
Solution: Use Selenium’s WebDriverWait with appropriate conditions to wait dynamically until specific elements are present or certain conditions are met.
Example:
python
# Instead of time.sleep(5), wait for a specific element that appears after login
dashboard_element = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "selector-for-dashboard")))
print("Login processing completed.")
7. Full Revised Code
Incorporating all the above suggestions, here's a revised version of your script:
python
8. Additional Recommendations
Run in Non-Headless Mode for Debugging: Keep the browser visible (headless mode disabled) while debugging to observe interactions.
Take Screenshots: Capture screenshots at various steps to verify that elements are being interacted with correctly.
python
driver.save_screenshot("step_name.png")
Use Explicit Waits Strategically: Replace time.sleep with explicit waits wherever possible to enhance reliability.
Handle Dynamic Content: If the website uses dynamic content loading (e.g., AJAX), ensure your script accounts for delays in content rendering.
Respect Website’s Terms of Service: Ensure that your scraping activities comply with Betika’s terms of service to avoid potential legal issues.
9. Understanding the Error Message
The error An error occurred: object of type 'NoneType' has no len() occurs because the scrape_aviator_history function returns None when an exception is caught. When the main function tries to execute len(multipliers), it fails because multipliers is None.
Solution: Modify the scrape_aviator_history function to return an empty list [] instead of None when an error occurs. This has been implemented in the revised code above.
10. Final Thoughts
Automating interactions with websites can be challenging due to dynamic content, frequent UI changes, and potential anti-bot measures. By implementing robust error handling, verifying selectors, and using Selenium’s features effectively, you can enhance the reliability of your scraper. Always ensure compliance with the website’s usage policies.
If you continue to face issues after implementing these changes, consider the following steps:
Update WebDriver and Browser: Ensure that both ChromeDriver and the Chrome browser are up-to-date.
Check for CAPTCHAs: Some websites use CAPTCHAs to prevent automated logins.
Use Proxies or User-Agent Rotation: To avoid being blocked, you might need to rotate proxies or user-agent strings.
Feel free to share any further error messages or issues you encounter, and I’d be happy to assist you further!
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 webdriver_manager.chrome import ChromeDriverManager
import time
# Function to scrape aviator history after logging in
def scrape_aviator_history():
# Set Chrome options (without headless mode)
options = webdriver.ChromeOptions()
# options.add_argument('--headless') # Uncomment to run in headless mode
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--disable-gpu')
# Initialize WebDriver with ChromeDriverManager
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
try:
# Step 1: Open Betika login page
driver.get("https://betika.com/en-ke/login")
print("Opened Betika login page")
# Step 2: Ensure elements are present and interactable
wait = WebDriverWait(driver, 20)
# Example: Close any obstructive modal
try:
close_modal = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.close-modal")))
close_modal.click()
print("Closed modal.")
except:
print("No modal to close.")
# Wait until phone input is clickable
phone_input = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#login-phone")))
print("Phone input is clickable.")
# Wait until password input is clickable
password_input = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#login-password")))
print("Password input is clickable.")
# Step 3: Enter phone number using send_keys
phone_input.clear()
phone_input.send_keys('0703972766')
print("Phone number entered.")
# Step 4: Enter password using send_keys
password_input.clear()
password_input.send_keys('ComplexPass123!')
print("Password entered.")
# Step 5: Click login button
login_button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[type='submit']")))
print("Login button is clickable.")
login_button.click()
print("Clicked login button.")
# Step 6: Wait for login to process by checking for an element that appears post-login
try:
profile_icon = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "selector-for-profile-icon")))
print("Login successful.")
except:
print("Login failed or profile icon not found.")
return []
# Step 7: Navigate to Aviator page after login
driver.get("https://betika.com/en-ke/aviator")
print("Navigated to Aviator page.")
# Step 8: Wait for the game-play div to appear
game_play = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.game-play")))
print("Game-play div found.")
# Step 9: Navigate to the history div
history_container = game_play.find_element(By.CSS_SELECTOR, "div.result-history.disabled-on-game-focused.my-2")
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")
# Step 10: Find all bubble multiplier elements
multiplier_elements = payouts_block.find_elements(By.CSS_SELECTOR, "app-bubble-multiplier.payout.ng-star-enabled")
# Step 11: Collect the multiplier values
multipliers = []
for element in multiplier_elements:
try:
# Find the inner div with the multiplier value
bubble_div = element.find_element(By.CSS_SELECTOR, "div.bubble-multiplier.font-weight-bold")
# Extract the multiplier text
multiplier = bubble_div.text
multipliers.append(multiplier)
except Exception as e:
print(f"Error processing element: {e}")
continue
return multipliers
except Exception as e:
print(f"An error occurred during scraping: {e}")
return []
finally:
# Always quit the driver
driver.quit()
# Main function to run the scraper
def main():
try:
multipliers = scrape_aviator_history()
print(f"Found {len(multipliers)} multipliers:")
print(multipliers)
except Exception as e:
print(f"An error occurred: {e}")
# Run the main function
if __name__ == "__main__":
main()