Python XML 体育运动员

Python XML sports players

我正在尝试打印此 XML http://api.cbssports.com/fantasy/players/list?version=3.0&SPORT=basketball

中每个球员的名字、姓氏、职业队和标题

到目前为止这是我的代码,但它不起作用

from urllib2 import Request, urlopen, URLError
import xml.etree.ElementTree as ET

request = Request('http://api.cbssports.com/fantasy/players/list?version=3.0&SPORT=basketball')

try:
   response = urlopen(request)
   tree = ET.parse(response)
   root = tree.getroot()
   for player in root.findall('.//players'):
      firstname = player.find('firstname').text
      lastname = player.find('lastname').text
      print firstname, lastname
except URLError, e:
    print 'error:', e

我认为错误出在 for 循环语句中,因为 firstname 不是玩家的直接 child,它的 parent 是玩家 ID

在上下文、当前元素内的任意位置添加双斜线。你需要迭代 player 元素而不是 players:

for player in root.findall('.//players/player'):
    firstname = player.findtext('.//firstname')
    lastname = player.findtext('.//lastname')