我正在使用 Python 使用 Steam 的 API 提取数据。我有一个随机生成的 Steam ID 列表。问题是,并非所有这些 ID 都指向有效帐户。当我尝试访问没有对象值的帐户时,程序给了我一个“KeyError”。Steam API 将为任何请求输出一个 ['response'] 级别对象,因此当我使用该最高级别进行打印时,我将获得每个请求的响应。但是,如果我再上一层(例如 ['response']['game_count']),当程序到达没有任何 ['game_count'] 值的帐户时,程序将失败。我如何告诉 python 跳过这些帐户?
示例输出:
带有游戏的帐户(删除了额外的回报以提高可读性)
{
"response": {
"game_count": 1,
"games": [
{
"appid": 205790,
"playtime_forever": 0
}
]
}
没有游戏的账号
{
"response": {
}
}
我当前的代码:
import urllib2, random, sys, json
list = open('d:\python\SteamUserIDs.txt').read().splitlines()
SteamID = str(list)
for SteamID in list[0:10:1]:
request = urllib2.Request('http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=05475AE5A8410CE01236A8A29E1DEE8E&steamid=%s&format=json' %SteamID, headers={"User-Agent": "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36"})
response = json.load(urllib2.urlopen(request))
request2 = urllib2.Request('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0001/?key=05475AE5A8410CE01236A8A29E1DEE8E&steamids=%s&format=json' %SteamID, headers={"User-Agent": "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36"})
response2 = json.load(urllib2.urlopen(request2))