简体   繁体   中英

How to get a label text using Watir

I'll have HTML

<div class="checklistbox HOTELS" name="HOTELS">                    
    <label><input type="checkbox" value="1" filters="" />Cat</label>
    <label><input type="checkbox" value="2" filters="" />Dog</label>
    <label><input type="checkbox" value="3" filters="" />Pony</label>
    <label><input type="checkbox" value="4" filters="" />black cat</label>
 </div>

How I can get a text from label, if label contains an unchecked checkbox?

browser.checkboxes(:xpath => '//*[@id="HOTELSCONTAINER"]/td[4]/div[2]/label/input').each do |l|
    if l.set? == false
        -- Get a label text -- 
    end
end

There is answer:

@i = 0
loop do 
    @i = @i + 1
    if (browser.checkbox(:xpath => '//*[@id="HOTELSCONTAINER"]/td[4]/div[2]/label[' + @i.to_s + ']/input').exists?)
        if  browser.checkbox(:xpath => '//*[@id="HOTELSCONTAINER"]/td[4]/div[2]/label[' + @i.to_s + ']/input').set? == false
                puts browser.element(:xpath => '//*[@id="HOTELSCONTAINER"]/td[4]/div[2]/label[' + @i.to_s + ']').text           
        end
    else
        break
    end
end 

You could:

  1. Find the checkboxes that are unchecked
  2. Navigate to their parent, which would be label
  3. Check the text of the label element.

One way would be to use a series of rejects/maps:

labels = browser.div(class: 'HOTELS').checkboxes.reject(&:set?).map(&:parent).map(&:text)
p labels
#=> ["Cat", "Dog", "Pony", "black cat"]

It might be more readable to combine the maps:

labels = browser.div(class: 'HOTELS').checkboxes.reject(&:set?).map { |box| box.parent.text }
p labels
#=> ["Cat", "Dog", "Pony", "black cat"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM