![](/img/trans.png)
[英]Python3 xml parsing and information extracting with ElementTree
[英]XML extracting parsing with ElementTree
我試圖從這個URL解析一些XML數據: http : //py4e-data.dr-chuck.net/comments_42.xml ,返回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)
我知道這里有一些基本問題,但我一直在嘗試並且沒有成功修改我的代碼。 我收到一個TypeError如下:
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
構造函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.