この記事では、Steamworks Web APIの IUserReviewsService/GetAppReviews/v1 を使い、Steamレビューの評価サマリーやレビュー本文をPythonで取得する方法をまとめます。
旧 https://store.steampowered.com/appreviews/{appid} は停止済みです。この記事の掲載コードは、現在の api.steampowered.com の方式へ更新しています。
自分のデータに合う実行経路を選ぶ
以下はWindows PowerShellでの手順です。Python 3.10以上を用意し、必要なファイルを保存したフォルダーをエクスプローラーで開き、アドレス欄に powershell と入力してEnterを押します。Get-Location で作業フォルダーを確認してください。
以下はSteamへの通信が必要ですが、APIキーは不要です。匿名アクセスには低い共有レート制限があるため、403や429が返った場合は制限回避をせず、時間を置いてください。CSVが既にある方は 取得なしの可視化、取得せず練習する方は 架空サンプルへ進んでください。
分析へ渡すなら条件記録付き実用版を選ぶ
実用版コード1個を collect_steam_reviews.py に保存します。AppIDと条件をそのファイルで確認し、下を実行します。基本例の定義コードを足す必要はありません。
python -m pip install requests
python collect_steam_reviews.py動きを段階ごとに学ぶなら基本例を選ぶ
「評価サマリーを取得する」→「レビュー本文を取得する」→「cursorでページングする」→「CSVに保存する」の4コードを順に steam_reviews.py へ保存します。基本例と実用版は代替経路です。
python -m pip install requests
python steam_reviews.py両経路とも保存CSVは作業フォルダー内の outputs/steam_reviews.csv です。基本例は同名CSVを上書きするので過去分を退避してください。実用版は既存ファイルがあれば停止し、outputs/steam_reviews.metadata.json も作ります。
最大5ページの教材であり、全件取得でも無作為標本でもありません。total_matching や初回の query_summary はAPIの参考件数で、重複除外後のCSV保存件数とは区別してください。
掲載コードと詳しい条件
Steamworks公式のIUserReviewsServiceで、GetAppReviews/v1 の取得条件を input_json に渡します。既存のSteam Web API、Storefrontの appdetails とは別のレビュー取得Methodです。
この例は filter=1(Recent)、review_type=0(All)、purchase_type=1(All)、languages=["japanese"] を使います。filter_offtopic_activity=true としてオフトピック活動を除外します。全件走査には不向きなHelpful(filter=0)は使いません。
評価サマリーを取得する
最初のコードはimport・Endpoint・共通条件・get_page() を定義し、初回ページのquery_summary と total_matching を表示します。新APIには旧方式の success fieldがなく、JSONの response envelopeを確認します。
"""Four-step basic example for the Steam review acquisition article."""
import csv
import json
import time
from pathlib import Path
import requests
APPID = 2246340
URL = "https://api.steampowered.com/IUserReviewsService/GetAppReviews/v1/"
BASE_CONDITIONS = {
"filter": 1, # Recent
"languages": ["japanese"],
"review_type": 0, # All
"purchase_type": 1, # All
"filter_offtopic_activity": True,
}
def get_page(cursor="*", num_per_page=100):
input_data = {
**BASE_CONDITIONS,
"appid": APPID,
"cursor": cursor,
"num_per_page": num_per_page,
}
response = requests.get(
URL,
params={
"format": "json",
"input_json": json.dumps(
input_data, ensure_ascii=False, separators=(",", ":")
),
},
timeout=(10, 30),
)
if response.status_code in (403, 429):
raise RuntimeError(
f"利用制限を受けました(HTTP {response.status_code})。"
"時間を置いて再実行してください。"
)
response.raise_for_status()
try:
payload = response.json()
except ValueError as exc:
raise RuntimeError("応答がJSONではありません。") from exc
body = payload.get("response") if isinstance(payload, dict) else None
if not isinstance(body, dict) or not isinstance(body.get("reviews"), list):
raise RuntimeError("Steam APIの応答形式が想定と異なります。")
return body
# 1. 評価サマリーを取得する。query_summaryは初回cursor="*"で確認する。
first = get_page(cursor="*", num_per_page=1)
print(first.get("query_summary"))
print("参考件数 total_matching:", first.get("total_matching"))レビュー本文を取得する
このコードは1番目で定義した get_page() を使います。author.num_games_owned は新APIで提供されないため、0として補いません。
# 2. レビュー本文を取得する。
first = get_page(cursor="*", num_per_page=20)
for review in first["reviews"][:3]:
print(review["voted_up"], review["review"][:100])cursorでページングする
cursor は初回に *、次回以降はレスポンスの値をそのまま渡します。空の一覧、次cursorの欠落・同値で終了し、最大5ページに達した場合も停止します。HTTPエラーや不正なJSONは0件扱いにしません。
# 3. cursorで最大5ページだけ取得する(全件取得ではない)。
reviews = []
cursor = "*"
for page in range(1, 6):
body = get_page(cursor=cursor, num_per_page=100)
batch = body["reviews"]
reviews.extend(batch)
if not batch:
break
next_cursor = body.get("cursor")
if not next_cursor or next_cursor == cursor:
break
cursor = next_cursor
if page < 5:
time.sleep(1)
print("取得行数:", len(reviews))CSVに保存する
4番目は3番目の reviews に依存します。0件でも列名付きCSVを作り、保存直後に再読込件数を照合します。
# 4. CSVへ保存し、再読込する。基本例は既存CSVを上書きする。
fieldnames = [
"recommendationid",
"voted_up",
"review",
"timestamp_created",
"timestamp_updated",
"playtime_forever",
"playtime_at_review",
"language",
]
rows = []
for review in reviews:
author = review.get("author", {})
rows.append(
{
"recommendationid": review.get("recommendationid"),
"voted_up": review.get("voted_up"),
"review": review.get("review"),
"timestamp_created": review.get("timestamp_created"),
"timestamp_updated": review.get("timestamp_updated"),
"playtime_forever": author.get("playtime_forever"),
"playtime_at_review": author.get("playtime_at_review"),
"language": review.get("language"),
}
)
csv_path = Path("outputs/steam_reviews.csv")
csv_path.parent.mkdir(parents=True, exist_ok=True)
with csv_path.open("w", encoding="utf-8-sig", newline="") as handle:
writer = csv.DictWriter(handle, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
with csv_path.open(encoding="utf-8-sig", newline="") as handle:
reader = csv.DictReader(handle)
assert reader.fieldnames == fieldnames
saved_count = sum(1 for _ in reader)
assert saved_count == len(rows)
print("保存先:", csv_path.resolve())
print("再読込で確認した件数:", saved_count)
if not rows:
print("0件のため、列名だけのCSVを保存しました。条件を確認してください。")CSVの playtime_forever と playtime_at_review は各reviewの author 内から取得します。欠損は空欄として扱い、0に置き換えません。
公開記事に使うときの注意
- レビュー本文を長文転載しない
- 特定ユーザーを追跡・特定しない
- 取得条件、言語、取得日、保存件数を明記する
- 最大5ページを全Steamレビューとして扱わない
- 機械翻訳や要約を使う場合は、誤読の可能性を残す
取得条件も残す実用版:CSVとmetadataをセットで保存
ここからは上の最小手順に代わる実用版です。前のPython実行の変数には依存しません。以下全文を collect_steam_reviews.py として保存してください。
"""Steamworks IUserReviewsService review collector used by the article example.
This educational script intentionally stops after a bounded number of pages.
It does not claim to download every Steam review.
"""
from __future__ import annotations
import csv
import hashlib
import io
import json
import time
from datetime import datetime, timezone
from pathlib import Path
import requests
API_URL = "https://api.steampowered.com/IUserReviewsService/GetAppReviews/v1/"
FIELDS = [
"recommendationid",
"voted_up",
"review",
"timestamp_created",
"timestamp_updated",
"playtime_forever",
"playtime_at_review",
"language",
]
REQUEST_CONDITIONS = {
"filter": 1, # Recent
"languages": ["japanese"],
"review_type": 0, # All
"purchase_type": 1, # All
"num_per_page": 100,
"filter_offtopic_activity": True,
}
def request_page(appid, cursor, get=requests.get):
request_body = {
**REQUEST_CONDITIONS,
"appid": int(appid),
"cursor": cursor,
}
response = get(
API_URL,
params={
"format": "json",
"input_json": json.dumps(
request_body, ensure_ascii=False, separators=(",", ":")
),
},
timeout=(10, 30),
)
if response.status_code in (403, 429):
raise RuntimeError(
f"Steam APIの利用制限を受けました(HTTP {response.status_code})。"
"時間を置いてから再実行してください。"
)
response.raise_for_status()
try:
payload = response.json()
except ValueError as exc:
raise RuntimeError("Steam APIの応答がJSONではありません。") from exc
body = payload.get("response") if isinstance(payload, dict) else None
if not isinstance(body, dict) or not isinstance(body.get("reviews"), list):
raise RuntimeError("Steam APIの応答形式が想定と異なります。")
if body.get("cursor") is not None and not isinstance(body["cursor"], str):
raise RuntimeError("Steam APIのcursor形式が想定と異なります。")
if body.get("query_summary") is not None and not isinstance(
body["query_summary"], dict
):
raise RuntimeError("Steam APIのquery_summary形式が想定と異なります。")
return body
def normalize_review(source):
if not isinstance(source, dict) or not isinstance(source.get("author"), dict):
raise ValueError("レビューまたはauthorがありません。")
rid = str(source.get("recommendationid", "")).strip()
if not rid.isdigit():
raise ValueError("レビューIDが不正です。")
author = source["author"]
return {
"recommendationid": rid,
"voted_up": source.get("voted_up"),
"review": source.get("review"),
"timestamp_created": source.get("timestamp_created"),
"timestamp_updated": source.get("timestamp_updated"),
"playtime_forever": author.get("playtime_forever"),
"playtime_at_review": author.get("playtime_at_review"),
"language": source.get("language"),
}
def collect(appid, max_pages=5, get=requests.get, pause=time.sleep):
if not isinstance(appid, int) or appid < 1:
raise ValueError("appidは1以上の整数にしてください。")
if not isinstance(max_pages, int) or max_pages < 1:
raise ValueError("max_pagesは1以上の整数にしてください。")
started = datetime.now(timezone.utc).isoformat()
cursor = "*"
unique = {}
raw_count = duplicates = conflicts = 0
first_summary = None
first_total_matching = None
termination_reason = "page_limit"
fetched_pages = 0
for page in range(1, max_pages + 1):
body = request_page(appid, cursor, get=get)
fetched_pages = page
batch = body["reviews"]
if page == 1:
first_summary = body.get("query_summary")
first_total_matching = body.get("total_matching")
for source in batch:
row = normalize_review(source)
rid = row["recommendationid"]
raw_count += 1
if rid in unique:
duplicates += 1
conflicts += int(row != unique[rid])
else:
unique[rid] = row # 同一IDは最初に受け取った内容を維持
if not batch:
termination_reason = "empty_response"
break
following = body.get("cursor")
if not following:
termination_reason = "missing_cursor"
break
if following == cursor:
termination_reason = "same_cursor"
break
cursor = following
if page < max_pages:
pause(1)
metadata = {
"api": "IUserReviewsService/GetAppReviews/v1",
"endpoint": API_URL,
"appid": str(appid),
"started_at": started,
"finished_at": datetime.now(timezone.utc).isoformat(),
"sent_parameters": REQUEST_CONDITIONS,
"first_cursor": "*",
"max_pages": max_pages,
"fetched_pages": fetched_pages,
"termination_reason": termination_reason,
"raw_rows": raw_count,
"saved_rows": len(unique),
"duplicate_rows": duplicates,
"conflicting_duplicate_rows": conflicts,
"duplicate_policy": "first_seen_by_recommendationid",
"first_query_summary": first_summary,
"first_total_matching": first_total_matching,
"unavailable_fields": ["author.num_games_owned"],
"scope": "bounded API result, not all reviews or a random sample",
}
return list(unique.values()), metadata
def save(rows, metadata, path=Path("outputs/steam_reviews.csv")):
path = Path(path)
sidecar = path.with_suffix(".metadata.json")
if path.exists() or sidecar.exists():
raise FileExistsError("以前のCSVとmetadataをセットで退避してください。")
buffer = io.StringIO(newline="")
writer = csv.DictWriter(buffer, fieldnames=FIELDS)
writer.writeheader()
writer.writerows(rows)
raw = buffer.getvalue().encode("utf-8-sig")
metadata = {
**metadata,
"csv_file": path.name,
"csv_sha256": hashlib.sha256(raw).hexdigest(),
}
path.parent.mkdir(parents=True, exist_ok=True)
# Exclusive creation keeps a race from overwriting an earlier successful file.
with path.open("xb") as handle:
handle.write(raw)
try:
with sidecar.open("x", encoding="utf-8") as handle:
json.dump(metadata, handle, ensure_ascii=False, indent=2)
except Exception:
path.unlink(missing_ok=True)
raise
with path.open(encoding="utf-8-sig", newline="") as handle:
saved_rows = list(csv.DictReader(handle))
if len(saved_rows) != len(rows):
raise RuntimeError("CSVの再読込件数が一致しません。")
print(path.resolve(), len(rows), "件", metadata["termination_reason"])
if __name__ == "__main__":
collected_rows, collected_metadata = collect(2246340, max_pages=5)
save(collected_rows, collected_metadata)保存先は outputs/steam_reviews.csv と outputs/steam_reviews.metadata.json。既存ファイルがあれば停止します。保存途中にmetadata作成が失敗した場合は、その実行で作成したCSVも削除し、片方だけを正常成果物として残しません。
同じ recommendationid は文字列IDで重複を除き、最初に受け取った内容を維持します。異なるreview IDの本文が完全一致しても別レビューとして維持します。後のページで同一IDの内容が異なる場合はmetadataの conflicting_duplicate_rows に記録します。
metadataには送信条件、取得開始・終了時刻、ページ上限、取得ページ数、終了理由、raw行数、保存件数、初回summary、total_matching、CSVのSHA-256を保存します。終了理由は page_limit、empty_response、missing_cursor、same_cursor を区別します。
403や429では保存処理へ進まず停止します。IP変更、APIキーの使い回し、session切替などの制限回避は行いません。新APIはAPIキーなしで利用できますが、匿名アクセスの低い共有レート制限を前提に、ページ間を1秒空けています。
保存したら、API通信なしで 投稿月別件数・好評率・投稿時プレイ時間を集計・可視化できます。
まとめ
現在のSteamレビュー取得には IUserReviewsService/GetAppReviews/v1 を使います。取得条件・cursor・終了理由・保存件数を記録し、限定した取得範囲として分析してください。APIの参考件数とCSVのユニーク保存件数は同じ指標ではありません。