2014-01-17 122 views
2

下面是我在後臺使用wget下載statsxml.jsp然後解析xml的示例代碼。我的問題是現在我需要解析多個XML URL,並且您可以在下面的代碼中看到我正在使用單個文件。任何人都可以在這裏幫助我如何做到這一點。使用ElementTree XML API解析URL XML

實例URL - http://www.trion1.com:6060/stat.xmlhttp://www.trion2.com:6060/stat.xmlhttp://www.trion3.com:6060/stat.xml

import xml.etree.cElementTree as ET 
tree = ET.ElementTree(file='statsxml.jsp') 

root = tree.getroot() 
root.tag, root.attrib 

print "root subelements: ", root.getchildren() 
root.getchildren()[0][1] 
root.getchildren()[0][4].getchildren() 

for component in tree.iterfind('Component name'): 
    print component.attrib['name'] 
+0

也許我理解有誤,但不能你只需要這些「多個URL」的數組,並調用這個片段(可能在一個函數或簡單地在循環)「爲array_of_urls中的每個url」? – user1349663

回答

6

您可以使用urllib2的下載和解析該文件以同樣的方式。對於例如前幾行會被更改爲:

import xml.etree.cElementTree as ET 
import urllib2 

for i in range(3): 
    tree = ET.ElementTree(file=urllib2.urlopen('http://www.trion%i.com:6060/stat.xml' % i)) 


    root = tree.getroot() 
    root.tag, root.attrib 

    # Rest of your code goes here....