使用Python解析xml文件中的特定元素

时间:2014-08-10 16:27:13

标签: python xml

我无法使用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']"))

我期待得到这个元素。但我得到了#34;没有"

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

XML page

有人可以帮我理解我做错了什么吗?

1 个答案:

答案 0 :(得分:1)

您应该测试的第一件事是如果您简化XPath会发生什么:

>>> print(root.find(".//field"))
None

那么,发生了什么?您没有field类型的任何元素。您有一个显式的命名空间,这意味着您拥有类型为“{http://www.librarything.com/} field”的元素。你可以很容易地看到这个:

>>> print(root.getchildren())
[<Element '{http://www.librarything.com/}item' at 0x1047580e8>]
>>> print(root.find(".//{http://www.librarything.com/}field"))
<Element '{http://www.librarything.com/}field' at 0x1047582c8>
>>> print(root.find(".//{http://www.librarything.com/}field[@type='5']"))
<Element '{http://www.librarything.com/}field' at 0x104758688>

如果您想了解更多信息,本网站上有很多关于ETree如何处理命名空间的问题(通过快速搜索,12看起来相关)和detailed information in the documentation ;试图在另一个答案中解释这一切只会导致对现有答案的较差回答。

相关问题