如何使用Python在XPath中以多行文本搜索内容?


问题内容

当我使用contains在一个元素的text()中搜索数据的存在时,它适用于纯数据,但当元素内容中有换行符,换行符/标记时,它不起作用。//td[contains(text(), "")]在这种情况下如何工作?谢谢!

XML:

<table>
  <tr>
    <td>
      Hello world <i> how are you? </i>
      Have a wonderful day.
      Good bye!
    </td>
  </tr>
  <tr>
    <td>
      Hello NJ <i>, how are you?
      Have a wonderful day.</i>
    </td>
  </tr>
</table>

Python:

>>> tdout=open('tdmultiplelines.htm', 'r')
>>> tdouthtml=lh.parse(tdout)
>>> tdout.close()
>>> tdouthtml
<lxml.etree._ElementTree object at 0x2aaae0024368>
>>> tdouthtml.xpath('//td/text()')
['\n      Hello world ', '\n      Have a wonderful day.\n      Good bye!\n    ', '\n      Hello NJ ', '\n    ']
>>> tdouthtml.xpath('//td[contains(text(),"Good bye")]')
[]  ##-> But *Good bye* is already in the `td` contents, though as a list.
>>> tdouthtml.xpath('//td[text() = "\n      Hello world "]')
[<Element td at 0x2aaae005c410>]

问题答案:

用途

//td[text()[contains(.,'Good bye')]]

说明

出现此问题的原因不是文本节点的字符串值是多行字符串-真正的原因是该td元素具有多个文本节点子级。

在提供的表达式中

//td[contains(text(),"Good bye")]

传递给函数的第一个参数contains()是一个节点集,其中包含多个文本节点

根据XPath 1.0规范(在XPath 2.0中,这只会引发类型错误),对需要字符串参数但传递给节点集的函数的求
值,仅接受节点中第一个节点的字符串值,设置

在这种情况下,传递的节点集中的第一个文本节点具有字符串值

 "
                 Hello world "

因此,比较失败,并且td未选择所需的元素

基于XSLT的验证

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
  <xsl:copy-of select="//td[text()[contains(.,'Good bye')]]"/>
 </xsl:template>
</xsl:stylesheet>

在提供的XML文档上应用此转换时:

<table>
      <tr>
        <td>
          Hello world <i> how are you? </i>
          Have a wonderful day.
          Good bye!
        </td>
      </tr>
      <tr>
        <td>
          Hello NJ <i>, how are you?
          Have a wonderful day.</i>
        </td>
      </tr>
</table>

计算XPath表达式,并将选定的节点(在本例中为一个)复制到输出

<td>
          Hello world <i> how are you? </i>
          Have a wonderful day.
          Good bye!
        </td>