2014-01-17 79 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....