0
votes

Using python and selenium to select an option in a combobox drop down ng select. I want to select the 'MALE' option in a dropdown select. I am trying to use XPath.

The code I use:

driver.find_element_by_id("sex_0").click()
driver.find_element_by_xpath("//*[contains(text(), 'MALE')]").click()

Copy and pasted the HTML:

Please Select OptionFEMALEMALE

Inspect element of the HTML:

<ng-select _ngcontent-uau-c14="" bindlabel="cdDescr" bindvalue="cd" class="custom ng-select ng-select-single ng-select-searchable ng-untouched ng-pristine ng-valid ng-select-opened ng-select-bottom" placeholder="Please Select Option" role="listbox" title="Please Select Option" id="sex_0">
 <div class="ng-select-container">
  <div class="ng-value-container"><div class="ng-placeholder">Please Select Option</div><!----><!---->
   <div class="ng-input" style="top: 0px;"><input role="combobox" type="text" autocomplete="ac08684b8af8" autocorrect="off" autocapitalize="off" aria-expanded="true" style="position: relative; top: 0px; left: -10px; padding-left: 10px; border: none !important; height: 45px; width: 468px;" aria-owns="ac08684b8af8" aria-activedescendant="ac08684b8af8-0"></div></div><!----><!---->
  <span class="ng-arrow-wrapper"><span class="ng-arrow"></span></span></div><!---->
 <ng-dropdown-panel class="ng-dropdown-panel ng-select-bottom" id="ac08684b8af8" style="opacity: 1;"><!---->
  <div class="ng-dropdown-panel-items scroll-host"><div></div>
   <div><!----><!---->
    <div class="ng-option ng-option-marked" role="option" aria-selected="false" id="ac08684b8af8-0"><!----><!----><span class="ng-option-label">FEMALE</span></div>
    <div class="ng-option" role="option" aria-selected="false" id="ac08684b8af8-1"><!----><!----><span class="ng-option-label">MALE</span></div>
<!----><!----><!----><!----></div></div><!----></ng-dropdown-panel></ng-select>

The problem:

It will select FEMALE instead of MALE because the XPath text "FEMALE" contains the text "MALE". I assume that the 'id="ac08684b8af8"' is randomly generated with each use, which means I can't use Selenium find element by id. I tried select using selenium but I get the error: "element of type ng select not select". Hence I used XPath. The "ng-option-marked" is just a feature when the cursor hovers above the dropdown selection.

How should I solve this problem?

1
Instead of contains use this driver.find_element_by_xpath("//*[text()='MALE']").click() - KunduK

1 Answers

0
votes

Answer is in the comments by KunduK.

driver.find_element_by_xpath("//*[text()='MALE']").click()