Creating an advanced and sophisticated Python script to search for underrated or hidden gem horror games involves several steps. We'll leverage multiple data sources such as Steam, itch.io, and possibly YouTube for view counts related to the games. We'll use APIs where available to fetch data efficiently and ensure our script is modular, maintainable, and robust.
Below is a comprehensive Python script that accomplishes this task. The script includes:
- Steam API Integration: Fetches horror games, their player counts, and reviews.
- itch.io Scraping: Gathers information about horror games listed on itch.io.
- YouTube API Integration: Retrieves view counts for gameplay videos related to the games.
- Data Processing: Analyzes the data to identify underrated or hidden gems based on specific criteria.
- Output: Presents the final list of recommended horror games.
Prerequisites
- Python 3.7+: Ensure you have Python installed.
- API Keys:
- Libraries: Install necessary Python libraries using
pip.
pip install requests pandas beautifulsoup4 google-api-python-client
Detailed Python Script
import requests
import pandas as pd
from bs4 import BeautifulSoup
from googleapiclient.discovery import build
import time
import logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
# Configuration
STEAM_API_KEY = 'YOUR_STEAM_API_KEY'
YOUTUBE_API_KEY = 'YOUR_YOUTUBE_API_KEY'
YOUTUBE_SEARCH_ENGINE = build('youtube', 'v3', developerKey=YOUTUBE_API_KEY)
# Constants
STEAM_APP_LIST_URL = 'https://api.steampowered.com/ISteamApps/GetAppList/v2/'
STEAM_APP_DETAILS_URL = 'https://store.steampowered.com/api/appdetails'
ITCH_IO_HORROR_URL = 'https://itch.io/games/tag/horror'
# Define headers for web scraping
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'
}
def fetch_steam_game_list():
logging.info("Fetching Steam game list...")
response = requests.get(STEAM_APP_LIST_URL)
if response.status_code == 200:
data = response.json()
games = data.get('applist', {}).get('apps', [])
logging.info(f"Fetched {len(games)} games from Steam.")
return games
else:
logging.error("Failed to fetch Steam game list.")
return []
def fetch_steam_game_details(app_ids):
logging.info("Fetching Steam game details...")
games_details = []
# Steam API allows batch requests, but for simplicity, we'll fetch individually
for app_id in app_ids:
params = {
'appids': app_id,
'cc': 'us', # Country code to get consistent data
'l': 'en' # Language
}
response = requests.get(STEAM_APP_DETAILS_URL, params=params)
if response.status_code == 200:
data = response.json()
app_data = data.get(str(app_id), {})
if app_data.get('success'):
details = app_data.get('data', {})
genres = [genre['description'] for genre in details.get('genres', [])]
if 'Horror' in genres:
games_details.append({
'app_id': app_id,
'name': details.get('name'),
'genres': genres,
'average_forever': details.get('average_forever', 0),
'owners': details.get('people_who_own', '0 - 0').split(' - ')[1],
'reviews': details.get('positive_reviews', 0),
'release_date': details.get('release_date', {}).get('date')
})
else:
logging.warning(f"Failed to fetch details for app ID {app_id}")
time.sleep(0.2) # To respect rate limits
logging.info(f"Retrieved details for {len(games_details)} horror games from Steam.")
return games_details
def scrape_itch_io_horror_games():
logging.info("Scraping itch.io for horror games...")
response = requests.get(ITCH_IO_HORROR_URL, headers=HEADERS)
if response.status_code != 200:
logging.error("Failed to scrape itch.io.")
return []
soup = BeautifulSoup(response.text, 'html.parser')
game_elements = soup.find_all('div', class_='game_cell')
horror_games = []
for game in game_elements:
title = game.find('div', class_='title').text.strip()
url = 'https://itch.io' + game.find('a', class_='game_title')['href']
# Additional scraping can be performed here to get more details
horror_games.append({
'name': title,
'url': url,
'platforms': 'Various',
'views': 'N/A' # itch.io does not provide view counts publicly
})
logging.info(f"Scraped {len(horror_games)} horror games from itch.io.")
return horror_games
def search_youtube_views(game_name):
logging.debug(f"Searching YouTube for views of: {game_name}")
try:
request = YOUTUBE_SEARCH_ENGINE.search().list(
q=game_name + " gameplay",
part='snippet',
type='video',
maxResults=1
)
response = request.execute()
if 'items' in response and len(response['items']) > 0:
video_id = response['items'][0]['id']['videoId']
video_response = YOUTUBE_SEARCH_ENGINE.videos().list(
part='statistics',
id=video_id
).execute()
if 'items' in video_response and len(video_response['items']) > 0:
view_count = video_response['items'][0]['statistics'].get('viewCount', 0)
logging.debug(f"Found {view_count} views for {game_name}")
return int(view_count)
return 0
except Exception as e:
logging.warning(f"Error fetching YouTube views for {game_name}: {e}")
return 0
def fetch_youtube_views(games):
logging.info("Fetching YouTube view counts for Steam horror games...")
for game in games:
view_count = search_youtube_views(game['name'])
game['youtube_views'] = view_count
time.sleep(0.1) # To respect rate limits
logging.info("Completed fetching YouTube view counts.")
return games
def identify_underrated_games(steam_games, threshold_reviews=50, max_youtube_views=100000):
logging.info("Identifying underrated horror games...")
underrated = []
for game in steam_games:
reviews = game.get('reviews', 0)
youtube_views = game.get('youtube_views', 0)
if reviews >= threshold_reviews and youtube_views <= max_youtube_views:
underrated.append(game)
logging.info(f"Identified {len(underrated)} underrated horror games.")
return underrated
def main():
# Step 1: Fetch Steam game list
steam_games = fetch_steam_game_list()
if not steam_games:
logging.error("Exiting due to failure in fetching Steam games.")
return
# Step 2: Filter for horror games and fetch details
# Note: Fetching all Steam games is resource-intensive; consider optimizing
horror_app_ids = [game['appid'] for game in steam_games if 'horror' in game['name'].lower()]
# This is a naive filter; ideally, use genres from another API or dataset
# For demonstration, we'll proceed with this approach
steam_horror_games = fetch_steam_game_details(horror_app_ids)
if not steam_horror_games:
logging.error("No Steam horror games found. Exiting.")
return
# Step 3: Fetch YouTube view counts
steam_horror_games = fetch_youtube_views(steam_horror_games)
# Step 4: Identify underrated games based on criteria
underrated_games = identify_underrated_games(steam_horror_games)
# Step 5: Scrape itch.io for additional hidden gems (optional)
itch_horror_games = scrape_itch_io_horror_games()
# Step 6: Combine and present results
combined_games = underrated_games + itch_horror_games
df = pd.DataFrame(combined_games)
# Save to CSV
df.to_csv('underrated_horror_games.csv', index=False)
logging.info("Saved underrated horror games to 'underrated_horror_games.csv'")
# Display top 10 underrated games
print(df.head(10))
if __name__ == "__main__":
main()
Explanation of the Script
-
Imports and Configuration:
- Import necessary libraries for HTTP requests, data handling, web scraping, YouTube API access, and logging.
- Configure logging to monitor the script's progress and debug if necessary.
- Define constants such as API URLs and headers for web scraping.
-
Fetch Steam Game List:
fetch_steam_game_list() retrieves the complete list of Steam applications using the Steam API.
- It parses the JSON response to extract game details.
-
Fetch Steam Game Details:
fetch_steam_game_details(app_ids) takes a list of Steam app IDs and fetches detailed information for each game.
- It filters games that belong to the "Horror" genre.
- Gathers relevant data such as the number of players, reviews, and release date.
- Implements a delay between requests to respect Steam's rate limits.
-
Scrape itch.io for Horror Games:
scrape_itch_io_horror_games() scrapes the itch.io horror games page to extract game titles and URLs.
- Note: itch.io may not provide view counts publicly, so the script marks views as 'N/A'.
-
YouTube View Counts:
search_youtube_views(game_name) uses the YouTube Data API to search for gameplay videos related to the game and retrieves the view count of the top result.
fetch_youtube_views(games) iterates over the list of games and appends the YouTube view counts to each game's data.
-
Identify Underrated Games:
identify_underrated_games(steam_games, threshold_reviews, max_youtube_views) filters games based on criteria such as a minimum number of reviews and a maximum number of YouTube views.
- This helps in identifying games that have enough engagement but not overly popular, thus likely underrated.
-
Main Function:
- Orchestrates the execution of all steps.
- Combines data from Steam and itch.io.
- Saves the final list of underrated horror games to a CSV file and displays the top entries.
Notes and Considerations
-
API Rate Limits: Both Steam and YouTube APIs have rate limits. The script includes time.sleep() calls to avoid hitting these limits, but for production use, consider implementing more sophisticated rate limiting and error handling.
-
Genre Filtering: The script uses a naive approach to filter horror games by checking if 'horror' is in the game name. A more accurate method would involve fetching genre data from a comprehensive API or dataset.
-
Enhancements:
- Parallel Requests: Implement asynchronous requests to speed up data fetching.
- Additional Data Sources: Incorporate more platforms like itch.io, Game Jolt, or Metacritic for a broader search.
- Advanced Filtering: Use more nuanced criteria for identifying underrated games, such as user ratings, critical reviews, or social media mentions.
- GUI or Web Interface: Build a user-friendly interface to interact with the script.
-
Ethical Considerations: Ensure compliance with the terms of service of the APIs and websites you are accessing. Avoid excessive scraping which can lead to IP bans or legal issues.
Final Remarks
This script provides a solid foundation for searching and identifying underrated horror games by leveraging multiple data sources. Depending on your specific requirements and data availability, you can further refine and enhance the script to improve accuracy and performance.