首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法用lxml逐属性查找元素

无法用lxml逐属性查找元素
EN

Stack Overflow用户
提问于 2018-11-28 14:19:22
回答 1查看 2.8K关注 0票数 3

我正在使用欧洲空间局API对query (结果可以查看here)进行卫星图像元数据解析为python对象。

使用requests库,我可以成功地获得XML格式的结果,然后使用lxml读取内容。我能够找到元素,并如预期的那样探索树:

代码语言:javascript
复制
# loading the response into an ElementTree
tree = etree.fromstring(response.content)
root = tree.getroot()
ns = root.nsmap

# get the first entry element and its summary
e = root.find('entry',ns)
summary = e.find('summary',ns).text

print summary

>> 'Date: 2018-11-28T09:10:56.879Z, Instrument: OLCI, Mode: , Satellite: Sentinel-3, Size: 713.99 MB'

entry元素有几个日期后代,其attriubute名称的值不同。

代码语言:javascript
复制
for d in e.findall('date',ns):
    print d.tag, d.attrib

>> {http://www.w3.org/2005/Atom}date {'name': 'creationdate'} {http://www.w3.org/2005/Atom}date {'name': 'beginposition'} {http://www.w3.org/2005/Atom}date {'name': 'endposition'} {http://www.w3.org/2005/Atom}date {'name': 'ingestiondate'}

我想使用XPath语法[@attrib='value']获取初学者日期元素,但它只返回None。即使只是搜索具有name属性([@attrib])的日期元素,也不返回:

代码语言:javascript
复制
dt_begin = e.find('date[@name="beginposition"]',ns) # dt_begin is None
dt_begin = e.find('date[@name]',ns)                 # dt_begin is None

条目元素包括表现出相同行为的其他子元素,例如具有不同名称属性的多个str元素。

有没有人遇到过类似的事情,或者我遗漏了什么?我在lxml 4.2.4中使用Python 2.7.14

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-28 17:11:55

在使用谓词([@name="beginposition"])时,似乎需要显式前缀。下面是一个测试程序:

代码语言:javascript
复制
from lxml import etree

print etree.LXML_VERSION

tree = etree.parse("data.xml")  

ns1 = tree.getroot().nsmap
print ns1
print tree.find('entry', ns1)
print tree.find('entry/date', ns1)
print tree.find('entry/date[@name="beginposition"]', ns1)

ns2 = {"atom": 'http://www.w3.org/2005/Atom'}
print tree.find('atom:entry', ns2)
print tree.find('atom:entry/atom:date', ns2)
print tree.find('atom:entry/atom:date[@name="beginposition"]', ns2)

输出:

代码语言:javascript
复制
(4, 2, 5, 0)
{None: 'http://www.w3.org/2005/Atom', 'opensearch': 'http://a9.com/-/spec/opensearch/1.1/'}
<Element {http://www.w3.org/2005/Atom}entry at 0x7f8987750b90>
<Element {http://www.w3.org/2005/Atom}date at 0x7f89877503f8>
None
<Element {http://www.w3.org/2005/Atom}entry at 0x7f8987750098>
<Element {http://www.w3.org/2005/Atom}date at 0x7f898774a950>
<Element {http://www.w3.org/2005/Atom}date at 0x7f898774a7a0>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53521545

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档