You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python解析Steam Web API返回的JSON获取CS:GO玩家统计数据

How to Parse Steam Web API JSON for CS:GO Player Stats in Python

Hey there! Parsing Steam Web API responses to pull CS:GO player stats (like total_kills) is straightforward with Python—let’s walk through it step by step so you can extract exactly what you need, even filter down to only the stats you care about.

Step 1: Fetch the API Data First

First, you’ll need to use the requests library to pull data from the Steam Web API. If you don’t have it installed, run pip install requests in your terminal.

Here’s how to make the request (replace placeholders with your actual API key and target Steam ID):

import requests

# Replace these with your details
API_KEY = "your_steam_api_key_here"
STEAM_ID = "target_player_steam_id_here"
# appid=730 is for CS:GO—adjust for other games if needed
API_URL = f"https://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key={API_KEY}&steamid={STEAM_ID}"

# Fetch and validate the response
try:
    response = requests.get(API_URL)
    response.raise_for_status()  # Throws an error if the request fails (e.g., invalid key)
except requests.exceptions.RequestException as e:
    print(f"Failed to fetch data: {e}")
    exit()

Step 2: Parse the JSON Response

The API returns a JSON string, which we can convert directly into a Python dictionary using .json():

stats_data = response.json()

Most Steam API responses for player stats follow a nested structure: playerstats → stats, where stats is a list of dictionaries (each with name for the stat label and value for the number).

Step 3: Extract Specific Fields (Like total_kills)

To get total_kills, we just need to loop through the stats list and find the entry where name matches our target. Here are two ways to do this:

Method 1: Simple Loop

# Access the stats list (with fallbacks in case keys are missing)
player_stats = stats_data.get("playerstats", {}).get("stats", [])
total_kills = None

for stat in player_stats:
    if stat.get("name") == "total_kills":
        total_kills = stat.get("value")
        break

if total_kills:
    print(f"Total CS:GO Kills: {total_kills}")
else:
    print("Could not find total_kills stat (player may not have played CS:GO)")

Method 2: Concise Generator Expression

For a shorter approach, use a generator to grab the first matching stat:

total_kills = next((stat["value"] for stat in player_stats if stat["name"] == "total_kills"), None)

Step 4: Filter to Keep Only Desired Stats

If you want to pull multiple specific stats (e.g., total_kills, total_deaths, total_wins), you can filter the entire list down to just those entries:

# List of stats you want to keep
desired_stats = ["total_kills", "total_deaths", "total_wins", "total_time_played"]

# Create a dictionary with only your desired stats
filtered_stats = {}
for stat in player_stats:
    stat_name = stat.get("name")
    if stat_name in desired_stats:
        filtered_stats[stat_name] = stat.get("value")

# Print the result
print("Filtered Player Stats:")
for stat, value in filtered_stats.items():
    print(f"{stat}: {value}")

Full Example Script

Here’s all the code combined into a reusable script:

import requests

def fetch_steam_stats(api_key, steam_id, app_id=730):
    """Fetch player stats from Steam Web API"""
    url = f"https://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid={app_id}&key={api_key}&steamid={steam_id}"
    try:
        response = requests.get(url)
        response.raise_for_status()
        return response.json().get("playerstats", {}).get("stats", [])
    except requests.exceptions.RequestException as e:
        print(f"Request error: {e}")
        return []

def get_specific_stat(stats_list, stat_name):
    """Extract a single stat by name"""
    return next((stat["value"] for stat in stats_list if stat["name"] == stat_name), None)

def filter_desired_stats(stats_list, desired_names):
    """Filter stats to only include desired names"""
    return {stat["name"]: stat["value"] for stat in stats_list if stat["name"] in desired_names}

# Usage
if __name__ == "__main__":
    API_KEY = "your_api_key"
    STEAM_ID = "target_steam_id"
    
    player_stats = fetch_steam_stats(API_KEY, STEAM_ID)
    
    # Get total kills
    total_kills = get_specific_stat(player_stats, "total_kills")
    print(f"Total Kills: {total_kills}")
    
    # Filter multiple stats
    desired = ["total_kills", "total_deaths", "total_wins"]
    filtered = filter_desired_stats(player_stats, desired)
    print("\nFiltered Stats:", filtered)

Quick Notes

  • You’ll need a valid Steam Web API key (you can get this from Steam’s developer portal, no external links needed).
  • Always handle errors (like invalid API keys, missing stats, or network issues) to avoid crashes.
  • Adjust the appid parameter if you’re querying stats for other games (e.g., 440 for Team Fortress 2).

内容的提问来源于stack exchange,提问作者OwenHunter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:03:51