Python体育XML解析

时间:2015-03-18 21:31:21

标签: python xml

我正在尝试在以下XML文件中打印每个专业团队的属性http://api.cbssports.com/fantasy/pro-teams/?version=3.0&SPORT=basketball

现在我只是想显示昵称,但这甚至不起作用

继承我的代码

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

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

try:
    response = urlopen(request)
    tree = ET.parse(response)
    root = tree.getroot()
    for team in root.findall('pro_team'):
      nickname = team.get('nickname')
      print nickname
except URLError, e:
print 'error:', e

1 个答案:

答案 0 :(得分:1)

使用

root.findall('.//pro_team')

代替root.findall('pro_team')查找<pro_team>下的所有root元素。 root.findall('pro_team')会返回一个空列表,因为<pro_team>元素不是root直接子

此外,team.get用于检索team属性。昵称是 不是属性 1 ;它是一个儿童元素。所以请改用team.find('nickname')


1 如果昵称是属性,则XML看起来像

<pro_team nickname="Spurs">...</pro_team>

而不是

<pro_team><nickname>Spurs</nickname></pro_team>

import urllib2
import xml.etree.ElementTree as ET

url = 'http://api.cbssports.com/fantasy/pro-teams?version=3.0&SPORT=basketball'
request = urllib2.Request(url)

try:
    response = urllib2.urlopen(request)
    tree = ET.parse(response)
    root = tree.getroot()
    for team in root.findall('.//pro_team'):
        nickname = team.find('nickname').text
        print nickname
except URLError, e:
    print 'error:', e