8

这是我在这里的第一篇文章,因为我已经看到了很多很棒的答案,所以我想我会试一试。

我正在尝试使用 XPath 来获取 HTML 文档中的特定元素。以下是基于 Google 网页的示例:

<html>
  <head>
    <title>XPath Test</title>
  </head>
  <body>
    <form name='f'>
      <table>
        <tbody>
          <tr>
            <td>
              <input name='q' type="text" />
            </td>
          </tr>
        </tbody>
      </table>
    </form>
  </body>
</html>

使用上面的示例(为了寻求帮助而对其进行了简化),我希望能够找到 name='q' 的输入元素并且其祖先是 5 父级且 name='f '。

例如,如果我要使用位于http://ulti-swat.wikispaces.com的开源 Web 自动化测试库 SWAT 的语法来执行此操作,则语法如下:

|AssertElementExists|表达式|名称=q;parentElement.parentElement.parentElement.parentElement.parentElement.name=f|输入|

我刚开始学习 XPath,并试图了解如何将谓词与轴结合起来。可以用 XPath 做这样的表达式吗?如果是这样,有知识的人可以帮忙吗?

4

1 回答 1

15

你可以这样做:

//input[@name='q' and ancestor-or-self::*[@name='f']]
// -- input element whose name='q' and who has an ancestor with the name='f'

或者

//input[@name='q' and ../../../../../../*[@name='f']]
// -- input element whose name='q' and who is 5 parents up with the name='f'

您可以使用这个桌面XPath Visualizer来测试您的 XPath 表达式。可以在此处找到基本教程

于 2010-02-02T02:04:09.713 回答