使用python遍历xml以查找具有特定扩展名的url

2024-05-19 16:35:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我的xml如下所示:

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

我编写了以下代码来获取xml文件:

^{pr2}$

然后我想让这样的事情发生:

   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 **

但这就带来了一个错误。有人有更好的方法吗?在

谢谢!在


Tags: 文件代码txthttpurldocfoo链接
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'

坦白说,你最后一段代码很恶心。dom.getElementsByTagName('file')提供树中所有<file>元素的列表。。。重复一遍就行了。在

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

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

^{pr2}$

相关问题 更多 >