如何在不使用其 id 的情况下使用 Xpath 定位输入字段

How to locate, using Xpath, an input field without using its id

我正在使用具有以下 HTML 的网页,我想在其中使用 text_field 来识别 <span> 中的第一个 <input> 字段页面对象。

<div id="131:">  Please enter your name:
<span class="autocompspan " style="position:static;">
    <input style="position: static;" class="autocompinput yui-ac-input" id="132:" name="132:" 
    onfocus="juic.fire(&quot;132:&quot;,&quot;_focus&quot;,event);" 
    onchange="juic.fire(&quot;132:&quot;,&quot;_despatchChange&quot;,event);" 
    onblur="juic.fire(&quot;132:&quot;,&quot;_blur&quot;,event);" size="60" 
    onkeydown="juic.fire(&quot;132:&quot;,&quot;_onkeydown&quot;,event);" 
    onkeyup="juic.fire(&quot;132:&quot;,&quot;_onkeyup&quot;,event);" aria-disabled="false" value="" 
    role="combobox" aria-autocomplete="list" aria-owns="132:_divList" 
    aria-activedescendant="132:_divAD" findtype="proxy" delimchar="" hideusername="false" 
    fetchusername="false" autocomplete="off" type="text">
    <input value="" id="132:_hidden" name="132:_hidden" type="hidden">
</span>
</div>

如果我使用 :id => '132:' 来识别字段,一切正常。 IE。 text_field(:target_user_name, :id => '132:' ) 有效。

问题是这个 HTML 是由底层应用程序 (SAP) 生成的,它并不总是为 <input> 字段 id 生成相同的值,因此使用 id 不能依赖于一致地标识元素。 因此,鉴于上述 HTML 我还可以通过哪些其他方式可靠地找到此 <input> 字段。

我尝试了以下方法,none 其中有效。大部分都在等待元素定位时超时。

text_field(:target_user_name, :xpath => "//*[@class='autocompinput yui-ac-input' and @role = 'combobox']" )
text_field(:target_user_name, :xpath => "//*[@class='autocompinput' and @role = 'combobox']" )
text_field(:target_user_name, :xpath => "//span/input[@class='autocompinput yui-ac-input' and @role = 'combobox']" )
text_field(:target_user_name, :xpath => "//input[@class='autocompinput yui-ac-input' and @role = 'combobox']" )
text_field(:target_user_name, :class => 'autocompinput yui-ac-input')

有什么想法吗?

首先,Watir 旨在让您不必使用 XPATH。

这取决于页面上有多少不同的 elements/ids,但我发现使用正则表达式通常可以很好地处理动态生成的 ID。所以要么获取 id 并在其他地方使用它:

id = browser.text_field(id: /\d\d\d/).tr(':', '')

或者直接使用:

text_field(:target_user_name, id: /\d\d\d:/)

当一个元素没有唯一可识别的属性时,你应该看看它周围的元素。在这种情况下,有用户可见的文本可以帮助用户识别该字段的用途。相同的文本可用于标识 Watir 中的元素。

由于周围的 div 仅包含标签文本,您可以通过其文本搜索 div 并获得其中唯一的文本字段:

browser.div(text: 'Please enter your name:').text_field

作为页面对象访问器:

text_field(:target_user_name) { div_element(text: 'Please enter your name:').text_field_element }

在这种特殊情况下,您可以使用以下 xpath 检查 'Please enter your name:' 文本后的第一个输入字段:

//div[text()='Please enter your name:']//following::input[1]

一般来说,如果您遇到没有唯一标识符的字段,您可以依赖静态文本或字段,然后使用 xpath 函数,例如 following、preceding 等。