Search code examples
rubywatir-webdriverirb

Watir::Exception::UnknownObjectException: unable to locate element


This is the drop-down from where I will select the various contract type

This the DIV, UL and LI classes which I have used in the code

irb(main):128:0> li_count_in_ul9 = browser.div(:class => "select2-drop select2-display-none select2-with-searchbox select2-drop-active").ul(:class => "select2-results").lis(:class => "select2-results-dept-0 select2-result select2-result-selectable")
=> #<Watir::LICollection:0x000000028ac0d0 @parent=#<Watir::UList:0xfc812aa2 located=false selector={:class=>"select2-results", :tag_name=>"ul"}>, @selector={:class=>"select2-results-dept-0 select2-result select2-result-selectable", :tag_name=>"li"}>
irb(main):129:0> li_count_in_ul9[0].click
Watir::Exception::UnknownObjectException: unable to locate element, using {:class=>"select2-results-dept-0 select2-result select2-result-selectable", :tag_name=>"li", :index=>0}
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/watir-webdriver-0.9.3/lib/watir-webdriver/elements/element.rb:536:in `assert_element_found'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/watir-webdriver-0.9.3/lib/watir-webdriver/elements/element.rb:508:in `assert_exists'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/watir-webdriver-0.9.3/lib/watir-webdriver/elements/element.rb:114:in `click'
        from (irb):129
        from C:/Ruby23-x64/bin/irb.cmd:19:in `<main>'
irb(main):130:0> sleep 5
=> 5
irb(main):131:0>

Solution

  • The problem appears to be with the:

    browser.div(:class => "select2-drop select2-display-none select2-with-searchbox select2-drop-active")
    

    From the image of the HTML, that is not the div that contains the li elements. It is a sibling div that contains the elements. As it has an id, you could locate it via:

    browser.div(:id => "select2-drop")
    

    Then end result being:

    li_count_in_ul9 = browser.div(:id => "select2-drop").ul(:class => "select2-results").lis(:class => "select2-results-dept-0 select2-result select2-result-selectable")
    

    From the HTML shared, this might be over specified. You may simply be able to do:

    li_count_in_ul9 = browser.div(:id => "select2-drop").lis(:class => "select2-result-selectable")