XPath:按纯文本查找HTML元素

Mic*_*ann 6 html xpath

请注意:这个问题是一个更完善的版本以前的问题.

我正在寻找一个XPath,它允许我在HTML文档中找到具有给定纯文本的元素.例如,假设我有以下HTML:

<html>
<head>...</head>
<body>
    <someElement>This can be found</someElement>
    <nested>
        <someOtherElement>This can <em>not</em> be found most nested</someOtherElement>
    </nested>
    <yetAnotherElement>This can <em>not</em> be found</yetAnotherElement>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我需要通过文本搜索,并能够找到<someElement>使用以下XPath:

//*[contains(text(), 'This can be found')]
Run Code Online (Sandbox Code Playgroud)

我正在寻找一个类似的XPath,让我找到<someOtherElement><yetAnotherElement>使用文本"This can not be found".以下不起作用:

//*[contains(text(), 'This can not be found')]
Run Code Online (Sandbox Code Playgroud)

我知道这是因为嵌套em元素"扰乱""无法找到这个"的文本流.是否可以通过XPath在某种程度上忽略上述类似或类似的嵌套?

Mic*_*ann 10

您可以使用

//*[contains(., 'This can not be found')]
   [not(.//*[contains(., 'This can not be found')])]
Run Code Online (Sandbox Code Playgroud)

这个XPath由两部分组成:

  1. //*[contains(., 'This can not be found')]:运算符.将上下文节点转换为其字符串表示形式.因此,此部分选择其字符串表示中包含"无法找到"的所有节点.在上面的例子中,这是<someOtherElement>,<yetAnotherElement> 和: <body><html>.
  2. [not(.//*[contains(., 'This can not be found')])]:这将删除具有子元素的节点,该子元素仍包含纯文本"无法找到".它删除了不需要的节点<body>,<html>在上面的示例中.

您可以在这里尝试这些XPath .