我使用ElementTree嘗試從XML中提取大量值。使用python在xml中提取文本值
這裏是XML的一個樣本: -
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE playerstats>
<playerstats>
<steamID>76561197960964581</steamID>
<gameName>Team Fortress 2</gameName>
<stats>
<stat>
<name>Scout.accum.iNumberOfKills</name>
<value>1777</value>
</stat>
<stat>
<name>Scout.accum.iPlayTime</name>
<value>247469</value>
</stat>
<stat>
<name>Scout.accum.iPointCaptures</name>
<value>641</value>
</stat>
<stat>
<name>Soldier.accum.iNumberOfKills</name>
<value>1270</value>
</stat>
<stat>
<name>Soldier.accum.iPlayTime</name>
<value>94649</value>
</stat>
<stat>
<name>Spy.accum.iNumberOfKills</name>
<value>7489</value>
</stat>
<stat>
<name>Spy.accum.iPlayTime</name>
<value>1110582</value>
</stat>
</stats>
</playerstats>
還有更多的事情,但是這僅僅是一個樣品。
我想提取和總結所有與「* .accum.iPlayTime」有關的值,以計算總播放時間。明星暗示所有職業(如偵察兵,士兵等)。
到目前爲止我的代碼(包括我的一些嘗試): -
playerStatsKISA = urllib2.urlopen('http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=440&key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&steamid=xxxxxxxxxxxxxxxxx&format=xml')
statsTF2 = playerStatsTF2.read()
theStatsTF2 = ET.fromstring(statsTF2)
totalTimesTF2 = theStatsKISA.findtext("Scout.accum.iPlayTime") # Didn't find anything
print totalTimesKISA
totalTimesTF2 = theStatsKISA.findall("./stats/stat/name")
for indiv in totalTimesTF2: # Another failed attempt
print indiv.attrib # didn't extract anything, I gather because the text I'm after is not an attribute but a value?
if indiv.attrib == 'Scout.accum.iPlayTime':
print "got it" # would extract value here, but it would be long winded to do this then try and extract the next value I'm actually after.
我是從每個類獲取值,然後累加它的想法去。雖然我收集了,但可能會用一個*爲TF2類的名字來獲得所有的價值,但是在我第一次計算出如何從標籤中得到值之後,我會這樣做。我需要的價值。
希望這是有道理的。
謝謝。
非常好,乾淨,謝謝。 – Markus