【发布时间】:2014-10-03 12:54:05
【问题描述】:
我无法使用 python 检索以下 xml 中的性别字段。 我尝试了以下方法:
import xml.etree.ElementTree as ET
requests.get('http://www.librarything.com/services/rest/1.1/method=librarything.ck.getauthor&id=216&apikey=d231aa37c9b4f5d304a60a3d0ad1dad4')
root = ET.fromstring(req.text)
print(root.find(".//field[@type='5']"))
我期待获得该元素。但我得到“无”
<response stat="ok">
<ltml xmlns="http://www.librarything.com/" version="1.1">
<item id="216" type="author">
<author id="216" authorcode="clarkesusanna">...</author>
<url>http://www.librarything.com/author/216</url>
<commonknowledge>
<fieldList>
<field type="22" name="canonicalname" displayName="Canonical name">...</field>
<field type="20" name="biography" displayName="Short biography">...</field>
<field type="33" name="relationships" displayName="Relationships">...</field>
<field type="18" name="nationality" displayName="Nationality">...</field>
<field type="32" name="othernames" displayName="Other names">...</field>
<field type="17" name="occupations" displayName="Occupations">...</field>
<field type="9" name="education" displayName="Education">...</field>
<field type="6" name="placesofresidence" displayName="Places of residence">...</field>
<field type="44" name="birthplace" displayName="Birthplace">...</field>
<field type="31" name="legalname" displayName="Legal name">...</field>
<field type="4" name="awards" displayName="Awards and honors">...</field>
<field type="8" name="birthdate" displayName="Birthdate">...</field>
<field type="5" name="gender" displayName="Gender">
<versionList>
<version id="7537" archived="0" lang="eng">
<date timestamp="1191988667">Tue, 09 Oct 2007 23:57:47 -0400</date>
<person id="1496">
<name>felius</name>
<url>http://www.librarything.com/profile/felius</url>
</person>
<factList>
<fact>female</fact>
</factList>
</version>
</versionList>
</field>
</fieldList>
</commonknowledge>
</item>
<legal>
By using this data you agree to the LibraryThing API terms of service.
</legal>
</ltml>
</response>
有人可以帮我理解我做错了什么吗?
【问题讨论】:
-
欢迎来到 Stack Overflow!看起来您希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的程序员编写代码,但他们通常只会在发布者已经尝试自己解决问题时提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出和您实际获得的输出(控制台输出、堆栈跟踪、编译器错误 - 不管是什么适用的)。您提供的详细信息越多,您可能收到的答案就越多。
-
另外,请在此处包含 XML 的示例,而不是在外部站点上。
-
谢谢,我想我的问题现在更具体了。
-
@user3927351:是的,这是一个很好的问题。如果您进一步剥离 XML 并将其作为三引号字符串嵌入到您的示例代码中会更好,因此我们可以将您的示例复制并粘贴到 Python 解释器中以使其更易于调试。但是对于我的 +1 来说已经足够了。
-
你有一个命名空间的 XML 文档,见Parsing XML with namespace in Python ElementTree