XPath:通过*plain*text查找HTML元素

Mic*_*ann 9 python selenium xpath

请注意:这个问题的更精确版本,以及适当的答案可以在这里找到.

我想使用Selenium Python绑定在网页上查找具有给定文本的元素.例如,假设我有以下HTML:

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

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

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

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

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

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

pau*_*rth 18

你可以用//*[contains(., 'This can not be found')].

.在与"无法找到"之前,上下文节点将转换为其字符串表示形式.

因为你使用时要小心//*,所以它将匹配包含这个字符串的所有 englobing元素.

在您的示例中,它将匹配:

  • <someOtherElement>
  • <body>
  • 而且<html>!

您可以通过定位文档中的特定元素标记或特定部分(a <table><div>具有已知ID或类)来限制此操作


编辑OP的问题,评论如何找到与文本条件匹配的最嵌套元素:

这里接受的答案建议//*[count(ancestor::*) = max(//*/count(ancestor::*))]选择最嵌套的元素.我认为这只是XPath 2.0.

当与子字符串条件结合使用时,我可以使用此文档在此处进行测试

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

并使用此XPath 2.0表达式

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

它匹配包含"无法找到最嵌套"的元素.

可能有更优雅的方式来做到这一点.

  • @MichaelHerrmann,根据[这个SO答案](http://stackoverflow.com/questions/11135620/how-to-get-the-most-deeply-nested-element-nodes-using-xpath-implementation-wit)它是可能在XPath 2.0中使用`//*[count(ancestor ::*)= max(//*/count(ancestor ::*))]`(你还必须结合`contains()`test当然)但我无法测试XPath 2.0来确认. (2认同)