15

我正在尝试使用 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 中可行吗?我需要用不同的方式表达我想做的事吗?

4

2 回答 2

23

你想要那个吗?

//title[text()='Text 1']/../content/text()
于 2009-02-28T21:40:19.710 回答
16

使用

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

与目前公认的 Johannes Weiß 解决方案相比,这代表了至少两个改进:

  1. 避免使用非常昂贵的缩写“//”(通常会导致扫描整个 XML 文档),因为只要事先知道 XML 文档的结构就应该这样做。

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

于 2009-03-01T01:37:19.047 回答