简体   繁体   中英

Python NBA stats

I am trying to print the player ID's and PPG for each player in the following XML http://api.cbssports.com/fantasy/stats?version=3.0&timeframe=2014&period=ytd&SPORT=basketball

However when I print nothing is printed and I don't know why:

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 is not a direct child of player_stats .

Instead, iterate over player nodes, get the id from attrib dictionary. In order to ding PPG value, use findtext() :

for stats in root.findall('.//player_stats/player'):
    id = stats.attrib.get('id')
    PPG = stats.findtext('.//stat[@abbr="PPG"]')
    print id, PPG

Prints:

1992786 24.6
307818 12.2615384615385
555968 12.375
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM