XPath:按*plain*tex查找HTML元素

2024-03-29 12:43:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

<html>
    <head>...</head>
    <body>
        <someElement>This can be found</someElement>
        <someOtherElement>This can <em>not</em> be found</someOtherElement>
    </body>
</html>

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

//*[contains(text(), 'This can be found')]

我正在寻找一个类似的XPath,它允许我使用纯文本找到<someOtherElement>。以下操作不起作用:

//*[contains(text(), 'This can not be found')]

我理解这是因为嵌套的em元素“中断”了“找不到”的文本流。在某种程度上,通过xpath是否可以忽略上述嵌套或类似的嵌套?


Tags: 文本元素htmlnotbodybethiscan
1条回答
网友
1楼 · 发布于 2024-03-29 12:43:30

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

上下文节点.将在与“找不到”进行比较之前转换为其字符串表示形式。

但是要小心,因为您使用的是//*,所以它将匹配包含此字符串的所有englobing元素。

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

  • <someOtherElement>
  • 以及<body>
  • 还有<html>

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


编辑“如何找到与文本条件匹配的最嵌套元素的注释”中的操作题:

The accepted answer here建议//*[count(ancestor::*) = max(//*/count(ancestor::*))]选择嵌套最多的元素。我认为这只是XPath 2.0。

当与您的子字符串条件结合使用时,我可以使用此文档test it here

<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>

使用这个XPath 2.0表达式

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

并且它与包含“大多数嵌套都找不到”的元素匹配。

可能有一种更优雅的方法来做到这一点。

相关问题 更多 >