Python NBA 数据
Python NBA stats
我正在尝试打印以下每个玩家的玩家 ID 和 PPG XML http://api.cbssports.com/fantasy/stats?version=3.0&timeframe=2014&period=ytd&SPORT=basketball
但是当我打印时什么也没有打印,我不知道为什么:
from urllib2 import Request, urlopen, URLError
import xml.etree.ElementTree as ET
request = Request('http://api.cbssports.com/fantasy/stats?version=3.0&timeframe=2014&period=ytd&SPORT=basketball')
try:
response = urlopen(request)
tree = ET.parse(response)
root = tree.getroot()
for stats in root.findall('.//player_stats/stats'):
id = stats.get('player_id')
PPG = stats.get('stat abbr="PPG"')
print id, PPG
except URLError, e:
print 'error:', e
stats
不是 player_stats
.
的直系子代
相反,遍历 player
个节点,从 attrib
字典中获取 id
。为了 ding PPG
值,使用 findtext()
:
for stats in root.findall('.//player_stats/player'):
id = stats.attrib.get('id')
PPG = stats.findtext('.//stat[@abbr="PPG"]')
print id, PPG
打印:
1992786 24.6
307818 12.2615384615385
555968 12.375
...
我正在尝试打印以下每个玩家的玩家 ID 和 PPG XML http://api.cbssports.com/fantasy/stats?version=3.0&timeframe=2014&period=ytd&SPORT=basketball
但是当我打印时什么也没有打印,我不知道为什么:
from urllib2 import Request, urlopen, URLError
import xml.etree.ElementTree as ET
request = Request('http://api.cbssports.com/fantasy/stats?version=3.0&timeframe=2014&period=ytd&SPORT=basketball')
try:
response = urlopen(request)
tree = ET.parse(response)
root = tree.getroot()
for stats in root.findall('.//player_stats/stats'):
id = stats.get('player_id')
PPG = stats.get('stat abbr="PPG"')
print id, PPG
except URLError, e:
print 'error:', e
stats
不是 player_stats
.
相反,遍历 player
个节点,从 attrib
字典中获取 id
。为了 ding PPG
值,使用 findtext()
:
for stats in root.findall('.//player_stats/player'):
id = stats.attrib.get('id')
PPG = stats.findtext('.//stat[@abbr="PPG"]')
print id, PPG
打印:
1992786 24.6
307818 12.2615384615385
555968 12.375
...