[英]How to select a Radio button in Watir with label text?
Watir上的備忘單和文檔顯示類似這樣的內容以設置單選按鈕
b.radio(:id => "radio").set
如何根據旁邊的文本選擇單選按鈕?
有時,此文本在label標記內,有時在div / form標記內。 我們如何在Watir中處理呢?
(以下示例中CAPS中的標簽文本)
范例1:
<form action="">
<input type="radio" value="male" name="sex"/>
MALE
<br/>
<input type="radio" value="female" name="sex"/>
FEMALE
</form>
范例2:
<div class="isoversixteen_false_container">
<input id="isoversixteen_false" class="radio" type="radio" value="0" name="isoversixteen" autocomplete="off"/>
<label class="isoversixteen_false_label" for="isoversixteen_false">
<span class="label_main">UNDER 16</span>
</label>
</div>
<div class="isoversixteen_true_container">
<input id="isoversixteen_true" class="radio" type="radio" value="1" name="isoversixteen" autocomplete="off" checked="checked"/>
<label class="isoversixteen_true_label" for="isoversixteen_true">
<span class="label_main">16 OR OVER</span>
</label>
</div>
Orde關於使用input元素的屬性的評論是一個好主意,因為它最容易編程。 但是,要回答這個問題:
示例1-相鄰文本節點
在此示例中,所需文本在相鄰的文本節點中。 鑒於單選按鈕共享同一父對象,我認為最簡單的解決方案是使用XPath:
browser.radio(xpath: '//input[following-sibling::text()[1][normalize-space(.) = "MALE"]]').set
browser.radio(xpath: '//input[following-sibling::text()[1][normalize-space(.) = "FEMALE"]]').set
XPath說:
[1]
[normalize-space(.) = "FEMALE"]
示例2-標簽文字
在此示例中,復選框具有正確關聯的標簽元素-即復選框的ID與標簽的for屬性匹配。 Watir支持通過:label
locator通過其標簽文本來定位元素:
browser.radio(label: 'UNDER 16').set
browser.radio(label: '16 OR OVER').set
示例-第一個后跟非空白文本節點
如果您想要一個適用於兩個示例的解決方案,那么以下方法似乎可行:
browser.radio(xpath: '//input[following::text()[normalize-space(.) != ""][1][normalize-space(.) = "UNDER 16"]]').set
browser.radio(xpath: '//input[following::text()[normalize-space(.) != ""][1][normalize-space(.) = "16 OR OVER"]]').set
browser.radio(xpath: '//input[following::text()[normalize-space(.) != ""][1][normalize-space(.) = "MALE"]]').set
browser.radio(xpath: '//input[following::text()[normalize-space(.) != ""][1][normalize-space(.) = "FEMALE"]]').set
此處的目的是在復選框之后找到包含文本( [normalize-space(.) != ""][1]
部分)並且該文本與期望的文本( [normalize-space(.) = "UNDER 16"
部分)。
這是我的示例中的HTML結構:
<div class="radio-inline">
<label for="job_type">Second Type</label>
<input id="job_service" name="job" type="radio" value="remote">
</div>
通常我會選擇它:
@browser.input(:value => 'remote').click
但是,根據您的問題,我嘗試查看是否可以通過文本進行選擇。 我發現這可行,但可能取決於嵌套在div中的標簽。
@browser.label(:text => /Second Type/).click
“第二類型”的/周圍是由於HTML中有些奇怪的換行符,可能只用引號引起來。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.