为给定的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类型。

enter image description here

更新

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

解决方法

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