How to click a specified li for an autocomplete ul

2020-04-17 05:50发布

问题:

I'm using Selenium IDE for some test and trying to use it to select an specified option from an autocomplete. My problem is, the autocomplete is built in a <ul> and the two <li> possibles are identical. How to click a specified li? How to say to Selenium "click the first li" or "click the li with the text "apples"? I'm tried some ways that I found, but all are for other types of Selenium, and none are useful in Selenium IDE.

Thanks in advance and sorry for my bad english!

Here is the code:

<ul class="ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all" role="listbox" aria-activedescendant="ui-active-menuitem" style="z-index: 1003; top: 360.683px; left: 549.5px; display: block; width: 401px;">
  <li class="ac_item ui-menu-item" role="menuitem">
    <a class="clearfix ui-corner-all" tabindex="-1">
      <span class="c1">
        <b>Apple</b>
        <br>
        <span class="small secondary">Apples</span>
        </span>
      </span>
    </a>
  </li>
  <li class="ac_item ui-menu-item" role="menuitem">
    <a class="clearfix ui-corner-all" tabindex="-1">
      <span class="c1">
        <b>Orange</b>
        <br>
        <span class="small secondary">Oranges</span>
        </span>
    </span>
    </a>
  </li>
</ul>

回答1:

The Selenium API gives you a number of ways to accomplish this. Since you don't have a traditional dropdown, you can't use the select command. Here are two solutions that click the second element in the autocomplete.

I created this JSFiddle to test the solutions. The clicked element will turn red.

Option 1: Use a CSS locator.

| Command               | Target                                               |
| open                  | http://jsfiddle.net/ansonhoyt/GYJW9/embedded/result/ |
| waitForElementPresent | css=ul.ui-autocomplete                               |
| click                 | css=ul.ui-autocomplete li.ui-menu-item:nth-child(2)  |

Note: Runs fast, and most people are comfortable with CSS, but this example requires that the targeted browser support the CSS3 nth-child selector.

Option 2: Use an XPath locator.

| Command               | Target                                               |
| open                  | http://jsfiddle.net/ansonhoyt/GYJW9/embedded/result/ |
| waitForElementPresent | css=ul.ui-autocomplete                               |
| click                 | //ul[contains(@class,'ui-autocomplete')]/li[2]       |

Note: XPath are less familiar for most people and can be very slow compared to CSS locators, especially in IE.

For more ideas, check out the documentation for Selenium IDE on locating elements and on the available Selenese commands.