首页 > 解决方案 > 为给定的 xpath 编写 WATIR 等效代码

问题描述

我正在尝试为给定的 xpath 编写 watir 代码,但它单击了错误的按钮,下面给出的 xpath 完美运行。

@browser.element(xpath: "//div[text()='#{locator.strip}']/../following-sibling::div/input/following-sibling::div").click

WATIR 代码

@browser.div(text: locator.strip).parent.following_sibling(tag_name: 'div').input.following_sibling(tag_name: 'div').click

我正在尝试单击选择列表按钮以打开该选项,但它错误地单击了位于我的目标 select_list 下方的选择列表。谁能帮助我哪里出错了?如果你看到下面的图片,它必须打开标题,但它正在打开 ID 类型。

在此处输入图像描述

更新

<div class="v-csslayout v-layout v-widget spml-cell v-csslayout-spml-cell spml-property v-csslayout-spml-property span4 v-csslayout-span4">
  <div class="v-caption v-caption-spml-value v-caption-uppercase v-caption-editable" id="gwt-uid-43" for="gwt-uid-44">
    <div class="v-captiontext">Title</div>
  </div>
  <div role="combobox" class="v-filterselect v-widget spml-value v-filterselect-spml-value uppercase v-filterselect-uppercase editable v-filterselect-editable v-filterselect-prompt" id="ClientDetails/Title">
    <input type="text" class="v-filterselect-input" autocomplete="off" id="gwt-uid-44" aria-labelledby="gwt-uid-43" tabindex="0" dir="" style="width: 281px;">
    <div class="v-filterselect-button" aria-hidden="true" role="button"></div>
  </div>
</div>

标签: rubyseleniumwatir

解决方案


XPath 和 Watir 代码之间的区别在于它们如何解释元素的“文本”:

  • 在 XPath 中,//div[text()='#{locator.strip}']表示必须等于定位器的第一个文本节点。div
  • 在 Watir 中,div(text: locator.strip)表示所有文本节点的串联必须div等于定位器。

结果,您最终会从不同的元素开始:

  • XPath 开始于<div class="v-captiontext">Title</div>
  • Watir 开始于<div class="v-csslayout v-layout v-widget spml-cell v-csslayout-spml-cell spml-property v-csslayout-spml-property span4 v-csslayout-span4">

这种差异导致 Watir 导航到不同的父级,然后跳转到相邻的字段。

知道了这一点,如果您想尽可能接近您的 XPath,您可以将类定位器添加到初始 div:

@browser.div(text: locator.strip, class: 'v-captiontext').parent.following_sibling(tag_name: 'div').input.following_sibling(tag_name: 'div').click

但是,假设这些元素中没有任何其他文本(即与示例完全相同),Watir 已经给出了顶级元素。因此,您可以简单地执行以下操作:

@browser.div(text: locator.strip).div(class: 'v-filterselect-button').click

推荐阅读