如何匹配文本节点,然后使用XPath跟随父节点

时间:2009-02-28 21:33:20

标签: python html xpath lxml

我正在尝试使用XPath解析一些HTML。按照下面的简化XML示例,我想匹配字符串'Text 1',然后获取相关content节点的内容。

<doc>
    <block>
        <title>Text 1</title>
        <content>Stuff I want</content>
    </block>

    <block>
        <title>Text 2</title>
        <content>Stuff I don't want</content>
    </block>
</doc>

我的Python代码不稳定地抛出:

>>> from lxml import etree
>>>
>>> tree = etree.XML("<doc><block><title>Text 1</title><content>Stuff 
I want</content></block><block><title>Text 2</title><content>Stuff I d
on't want</content></block></doc>")
>>>
>>> # get all titles
... tree.xpath('//title/text()')
['Text 1', 'Text 2']
>>>
>>> # match 'Text 1'
... tree.xpath('//title/text()="Text 1"')
True
>>>
>>> # Follow parent from selected nodes
... tree.xpath('//title/text()/../..//text()')
['Text 1', 'Stuff I want', 'Text 2', "Stuff I don't want"]
>>>
>>> # Follow parent from selected node
... tree.xpath('//title/text()="Text 1"/../..//text()')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "lxml.etree.pyx", line 1330, in lxml.etree._Element.xpath (src/
lxml/lxml.etree.c:14542)
  File "xpath.pxi", line 287, in lxml.etree.XPathElementEvaluator.__ca
ll__ (src/lxml/lxml.etree.c:90093)
  File "xpath.pxi", line 209, in lxml.etree._XPathEvaluatorBase._handl
e_result (src/lxml/lxml.etree.c:89446)
  File "xpath.pxi", line 194, in lxml.etree._XPathEvaluatorBase._raise
_eval_error (src/lxml/lxml.etree.c:89281)
lxml.etree.XPathEvalError: Invalid type

这在XPath中是否可行?我是否需要以不同的方式表达我想要做的事情?

2 个答案:

答案 0 :(得分:23)

你想要吗?

//title[text()='Text 1']/../content/text()

答案 1 :(得分:16)

使用

string(/*/*/title[. = 'Text 1']/following-sibling::content)

与目前公认的JohannesWeiß解决方案相比,这代表至少两项改进

  1. 非常昂贵的缩写“//”(通常会导致整个XML文档被扫描)被避免,因为它应该是每当结构XML文档是事先知道的。

  2. 没有返回父级(避免使用位置步骤“/ ..”)