【发布时间】:2011-05-26 06:42:35
【问题描述】:
我正在使用 Amazon 的 API 来接收有关图书的信息。我正在尝试使用 lxml 来提取我的应用程序所需的 XML 文档的特定部分。 不过,我不确定如何使用 lxml。 这是据我所知:
root = etree.XML(response)
为 XML 文档创建一个 etree 对象。
XML 文档如下所示: http://pastebin.com/GziDkf1a 实际上有多个“项目”,但我只粘贴其中一个给你一个具体的例子。 对于每个项目,我想提取标题和 ISBN。我如何使用我拥有的 etree 对象来做到这一点?
<ItemSearchResponse><Items><Item><ItemAttributes><Title>I want this info</Title></ItemAttributes></Item></Items></ItemSearchResponse
<ItemSearchResponse><Items><Item><ItemAttributes><ISBN>And I want this info</ISBN></ItemAttributes></Item></Items></ItemSearchResponse
基本上,我不知道如何使用我的 etree 对象遍历树,我想学习如何。
编辑 1: 我正在尝试以下代码:
tree = etree.fromstring(response)
for item in tree.iterfind(".//"+AMAZON_NS+"ItemAttributes"):
print(item)
print(item.items()) # Apparently, there is nothing in item.items()
for key, value in item.items():
print(key)
print(value)
但我得到以下输出: http://dpaste.com/287496/
我添加了 print(item.items()),它似乎只是一个空列表。虽然每个项目都是一个元素,但由于某种原因,它们没有项目。
编辑 2: 我可以使用下面的代码来获取我想要的信息,但是看起来lxml必须有更简单的方法......(这种方式看起来效率不高):
for item in tree.iterfind(".//"+AMAZON_NS+"ItemAttributes"):
title_text = ""
author_text = ""
isbn_text = ""
for isbn in item.iterfind(".//"+AMAZON_NS+"ISBN"):
isbn_text = isbn.text
for title in item.iterfind(".//"+AMAZON_NS+"Title"):
title_text = title.text
for author in item.iterfind(".//"+AMAZON_NS+"Author"):
author_text = author.text
print(title_text + " by " + author_text + " has ISBN: " + isbn_text)
【问题讨论】:
-
您好,您好,您接受的答案无效。请参阅我对该答案的评论。请注意,我提供了一个 tested working 答案。