A fun web scraping project! I'll guide you through creating a script to scrape the Keno results website. Since the website uses dynamic content (numbers jumping out and updating in real-time), we'll need to use a tool that can render JavaScript and wait for the numbers to settle. For this, we'll use Selenium WebDriver with Python.
Before we begin, please ensure you:
- Have Python 3.7+ installed on your system.
- Install the required libraries by running:
pip install selenium pandas
- Download the ChromeDriver (or your preferred browser's driver) and add its location to your system's PATH. You can get it from: https://chromedriver.chromium.org/downloads (Match the driver version with your Chrome browser version).
Here's the step-by-step script. I'll use ChromeDriver in this example. If you prefer another browser, adjust the driver setup accordingly.
import os
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import pandas as pd
from datetime import datetime
# Set up ChromeDriver
options = webdriver.ChromeOptions()
options.add_argument('--headless') # Run in background; remove this line to see the browser in action
options.add_argument('--disable-gpu')
options.add_argument('--window-size=1920,1080') # Necessary for headless mode
driver = webdriver.Chrome(options=options)
# Target website
URL = "YOUR_KENO_RESULTS_WEBSITE_URL_HERE" # Replace this with the actual URL
def scrape_keno_results():
driver.get(URL)
print("Loaded the website...")
# Wait until the Keno board is visible (adjust the selector as needed)
try:
keno_board = WebDriverWait(driver, 15).until(
EC.visibility_of_element_located((By.CSS_SELECTOR, "SELECTOR_FOR_KENO_BOARD"))
)
print("Keno board found!")
except TimeoutException:
print("Keno board not found. Check the selector or website URL.")
driver.quit()
return
results = []
game_count = 0
max_games = 10 # Adjust how many games you want to scrape
while game_count < max_games:
try:
# Extract Game ID (adjust the selector)
game_id_element = WebDriverWait(driver, 10).until(
EC.visibility_of_element_located((By.CSS_SELECTOR, "SELECTOR_FOR_GAME_ID"))
)
game_id = game_id_element.text.strip()
print(f"Scraping Game ID: {game_id}")
# Wait for the numbers to settle (3-5 minutes).
# We'll check if the numbers stop changing by comparing two snapshots.
numbers_stabilized = False
last_numbers = []
wait_time = 120 # seconds (2 minutes should be enough; adjust if needed)
start_wait = time.time()
while not numbers_stabilized and (time.time() - start_wait) < wait_time:
# Extract Keno numbers (adjust the selector)
keno_numbers_elements = driver.find_elements(By.CSS_SELECTOR, "SELECTOR_FOR_EACH_KENO_NUMBER")
current_numbers = [num.text.strip() for num in keno_numbers_elements[:20]] # Get first 20 numbers
if current_numbers == last_numbers and len(current_numbers) == 20:
numbers_stabilized = True
print("Numbers stabilized:", current_numbers)
else:
last_numbers = current_numbers
time.sleep(5) # Check every 5 seconds
if not numbers_stabilized:
print(f"Numbers didn't stabilize for Game ID {game_id}. Skipping...")
continue
# Get timestamp
now = datetime.now()
date_str = now.strftime("%Y-%m-%d")
time_str = now.strftime("%H:%M:%S")
# Store the result
result = {
"Date": date_str,
"Time": time_str,
"Game_ID": game_id,
}
for i in range(20):
result[f"Number_{i+1}"] = int(current_numbers[i]) # Store numbers as integers
results.append(result)
game_count += 1
print(f"Game {game_count} scraped successfully.")
# Wait briefly before checking for the next game
time.sleep(10)
except Exception as e:
print(f"Error scraping game: {e}")
driver.quit()
return results
if __name__ == "__main__":
scraped_data = scrape_keno_results()
# Save to CSV
if scraped_data:
df = pd.DataFrame(scraped_data)
df.to_csv("keno_results.csv", index=False)
print("Data saved to keno_results.csv")
else:
print("No data scraped.")
Critical Steps & Adjustments:
-
Replace YOUR_KENO_RESULTS_WEBSITE_URL_HERE with the actual URL of the Keno results website.
-
Inspect the Website (Right-click → Inspect → Elements tab) and update the CSS Selectors in the script:
SELECTOR_FOR_KENO_BOARD: The container element holding the Keno board.
SELECTOR_FOR_GAME_ID: The element displaying the Game ID (e.g., #game-id, .game-id-class).
SELECTOR_FOR_EACH_KENO_NUMBER: Individual number elements (e.g., .keno-number, div.ball).
For example, if each Keno number is in a <div class="keno-ball">12</div>, your selector would be "div.keno-ball".
-
Tweak Wait Times:
wait_time (inside the loop) controls how long to wait for numbers to stabilize. If games update faster/slower, adjust this.
time.sleep(5) checks the numbers every 5 seconds. Reduce this if you want faster checks (at the cost of CPU).
-
Run in Non-Headless Mode (comment out options.add_argument('--headless')) to visually see the browser scrape data. Useful for debugging.
Output (CSV Structure):
The script saves data into keno_results.csv with columns:
Date,Time,Game_ID,Number_1,Number_2,...,Number_20
2024-10-16,14:30:00,G12345,7,11,14,...,68
2024-10-16,14:33:15,G12346,3,9,21,...,75
...
Legal Note: Always check the website's robots.txt (e.g., example.com/robots.txt) and Terms of Service before scraping. Some sites prohibit automated access.
Run the script, and it should start collecting Keno results for you! If you hit snags, share the website URL (if public) or the HTML structure, and I can help fine-tune the selectors. Happy scraping!