iTunes Top Songs & Albums Purchases Python Script

This Python script fetches and displays the current top songs or albums based on purchases from the iTunes Store. Users can select a category and the number of entries to view, with rankings clearly labeled to reflect purchase trends as of the check date.

Click to view script…
#!/usr/bin/env python3
# iTunes Top Purchases Scraper
# Purpose: Fetches and displays the current top songs or albums based on purchases from the iTunes Store.
# Note: This script shows purchase-based rankings, not streaming data.

import requests
from datetime import datetime

# Define categories with their display names and RSS feed paths
categories = {
    1: {'name': 'Top Songs (Purchases)', 'path': 'topsongs'},
    2: {'name': 'Top Albums (Purchases)', 'path': 'topalbums'}
}

def main():
    """Main function to run the iTunes Top Purchases Scraper."""
    # Inform the user that the data reflects purchases, not streaming
    print("Welcome! This script shows top songs or albums based on purchases from the iTunes Store (not streaming data).")
    
    # Display category options
    print("\nSelect a category:")
    for key, value in categories.items():
        print(f"{key}. {value['name']}")
    
    # Get and validate category choice
    choice_input = input("Enter the number of your choice: ")
    try:
        choice = int(choice_input)
        if choice not in categories:
            raise ValueError
    except ValueError:
        print("Invalid choice. Please run the script again and enter 1 or 2.")
        return
    
    category = categories[choice]
    category_name = category['name']
    
    # Get and validate number of entries
    limit_input = input("Enter the number of entries to display (1-100, default 10): ")
    if limit_input.strip() == "":
        limit = 10
    else:
        try:
            limit = int(limit_input)
            if limit < 1 or limit > 100:
                print("Limit must be between 1 and 100. Using default of 10.")
                limit = 10
        except ValueError:
            print("Invalid input. Using default of 10.")
            limit = 10
    
    # Construct the RSS feed URL
    url = f"https://itunes.apple.com/us/rss/{category['path']}/limit={limit}/json"
    
    # Record the current date and time
    check_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # Fetch data from the iTunes RSS feed
    try:
        response = requests.get(url)
        response.raise_for_status()
        data = response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error fetching data: {e}")
        return
    
    # Extract entries from the JSON response
    feed = data.get('feed', {})
    entries = feed.get('entry', [])
    
    if not entries:
        print("No data available for this category.")
        return
    
    # Display the results
    print(f"\n{category_name} as of {check_date}")
    print(f"{'Rank':<5} {'Name':<50} {'Artist':<30}")
    print("-" * 85)
    
    for i, entry in enumerate(entries, start=1):
        name = entry.get('im:name', {}).get('label', 'N/A')
        artist = entry.get('im:artist', {}).get('label', 'N/A')
        print(f"{i:<5} {name:<50} {artist:<30}")

if __name__ == '__main__':
    main()