【问题标题】:Iterate through xml to find url with specific extension with python遍历xml以使用python查找具有特定扩展名的url
【发布时间】:2012-07-10 21:56:01
【问题描述】:

我有一个从 url 下载的 xml 文件。然后我想遍历 xml 以找到指向具有特定文件扩展名的文件的链接。

我的 xml 看起来像这样:

<Foo>
    <bar>
        <file url="http://foo.txt"/>
        <file url="http://bar.doc"/>
    </bar>
</Foo>

我已经编写了这样的代码来获取 xml 文件:

import urllib2, re
from xml.dom.minidom import parseString

file = urllib2.urlopen('http://foobar.xml')
data = file.read()
file.close()
dom = parseString(data)
xmlTag = dom.getElementsByTagName('file')

然后我'想'让这样的东西工作:

   i=0
    url = ''
    while( i < len(xmlTag)):
         if re.search('*.txt', xmlTag[i].toxml() ) is not None:
              url = xmlTag[i].toxml()
         i = i + 1;

** Some code that parses out the url **

但这会引发错误。有人有更好方法的提示吗?

谢谢!

【问题讨论】:

    标签: python xml regex xml-parsing


    【解决方案1】:

    坦率地说,你的最后一段代码很恶心。 dom.getElementsByTagName('file') 为您提供树中所有 &lt;file&gt; 元素的列表...只需对其进行迭代。

    urls = []
    for file_node in dom.getElementsByTagName('file'):
        url = file_node.getAttribute('url')
        if url.endswith('.txt'):
            urls.append(url)
    

    顺便说一句,您永远不必使用 Python 手动进行索引。即使在极少数情况下您需要索引号,也只需使用 enumerate:

    mylist = ['a', 'b', 'c']
    for i, value in enumerate(mylist):
        print i, value
    

    【讨论】:

    • 是的,今天有点恶心。我上周刚拿起python。但这完美无缺!只需将 'url = file_node.getAttribute('urls')' 行更改为 'url = file_node.getAttribute('url')' ,它就像一个魅力。谢谢!
    【解决方案2】:

    使用lxmlurlparseos.path 的示例:

    from lxml import etree
    from urlparse import urlparse
    from os.path import splitext
    
    data = """
    <Foo>
        <bar>
            <file url="http://foo.txt"/>
            <file url="http://bar.doc"/>
        </bar>
    </Foo>
    """
    
    tree = etree.fromstring(data).getroottree()
    for url in tree.xpath('//Foo/bar/file/@url'):
        spliturl = urlparse(url)
        name, ext = splitext(spliturl.netloc)
        print url, 'is is a', ext, 'file'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-08
      • 1970-01-01
      • 1970-01-01
      • 2011-05-03
      • 2011-08-21
      • 2019-07-21
      相关资源
      最近更新 更多