XML 使用 ElementTree 提取解析

XML extracting parsing with ElementTree

我正在尝试从这个 url 中解析一些 XML 数据:http://py4e-data.dr-chuck.net/comments_42.xml,return Count 值并对提取的值求和。

import urllib as ur
import xml.etree.ElementTree as ET

url = input(('Enter location: '))
print'Retrieving:', url

data = ur.urlopen(url).read()
tree = ET.fromstring(data)
counts = tree.findall('.//count')

print('Count: ', sum(counts))
#print('Sum: ', sum_all)

我知道这里有一些基本问题,但我一直在尝试修改我的代码,但没有成功。我收到如下类型错误:

Enter location: 'http://py4e-data.dr-chuck.net/comments_42.xml'
Retrieving: http://py4e-data.dr-chuck.net/comments_42.xml
Traceback (most recent call last):
  File "extracting_xml.py", line 11, in <module>
    print('Count: ', sum(counts))
TypeError: unsupported operand type(s) for +: 'int' and 'Element'

您得到的错误是在总和 sum(counts) 中。相反,你应该这样做:

sum([int(el.text) for el in counts])

因为异常表明您正在尝试对找到的 Element 类型的节点求和,这些节点没有定义加法运算符。节点包含纯整数,因此将节点的文本转换为 int 然后求和就是您需要做的。

如果您的节点中有浮动,那么您将使用 float 构造函数。