它是一个ElementTreeElement
对象。
您还可以查看lxml API 文档,它有一个lxml.etree._Element
页面。该页面会告诉您该类上您可能想知道的每个属性和方法。
但是,我将从阅读lxml.etree
教程开始。
但是,如果该元素无法被索引,则它是一个空标签,并且没有要检索的子节点。
要通过 查找所有行Bernardo
,需要一个带有命名空间映射的 XPath 表达式。使用什么前缀并不重要,只要它是一个非空字符串lxml
,就会将它映射到正确的命名空间 URL:
nsmap = {'s': 'http://www.tei-c.org/ns/1.0'}
for line in tree.xpath('.//s:sp[@who="Barnardo"]/s:l/text()', namespaces=nsmap):
print line.strip()
这会提取标签<l>
中包含的元素中的所有文本。<sp who="Barnardo">
注意s:
标签名称的前缀,nsmap
字典告诉lxml
使用哪个命名空间。我打印了这些没有周围额外的空白。
对于您的示例文档,这给出了:
>>> for line in tree.xpath('.//s:sp[@who="Barnardo"]/s:l/text()', namespaces=nsmap):
... print line.strip()
...
Who's there?
Long live the king!
He.
'Tis now struck twelve; get thee to bed, Francisco.
Have you had quiet guard?
Well, good night.
If you do meet Horatio and Marcellus,
The rivals of my watch, bid them make haste.
Say,
What, is Horatio there?
Welcome, Horatio: welcome, good Marcellus.
I have seen nothing.
Sit down awhile;
And let us once again assail your ears,
That are so fortified against our story
What we have two nights seen.
Last night of all,
When yond same star that's westward from the pole
Had made his course to illume that part of heaven
Where now it burns, Marcellus and myself,
The bell then beating one,
In the same figure, like the king that's dead.
Looks 'a not like the king? mark it, Horatio.
It would be spoke to.
See, it stalks away!
How now, Horatio! you tremble and look pale:
Is not this something more than fantasy?
What think you on't?
I think it be no other but e'en so:
Well may it sort that this portentous figure
Comes armed through our watch; so like the king
That was and is the question of these wars.
'Tis here!
It was about to speak, when the cock crew.