Rafael
Rafael

Reputation: 3196

How to view text options within a dropdown menu

The HTML of the select list looks like:

<select name="date_range_month_start" id="date_range_month_start" data-width="109px" data-search="true" style="width: 109px; display: none;">
                    <option value="0">January</option>
                    <option value="9">October</option>
                    <option value="10" selected="selected">November</option>
                    <option value="11">December</option>
                 </select>

<div class="chosen-container chosen-container-single chosen-container-single-nosearch" style="width: 109px;" title="" id="date_range_month_start_chosen">
        <a class="chosen-single" tabindex="-1">
            <span>January</span>
                    <div><b></b>
                    </div>
                  </a>
    <div class="chosen-drop">...</div>
    </div>

However when I run:

month = driver.find_element_by_id('date_range_month_start_chosen')
month.click() ## make dropdown list visible in browser
mySelect = Select(driver.find_element_by_css_selector("#date_range_month_start"))
print([o.text for o in mySelect.options])

It prints: ['', '', '', '', '', '', '', '', '', '', '', ''] I've tried a few other things as well but so far have been entirely unsuccessful at printing what the text values in this drop down menu.

Upvotes: 0

Views: 541

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193068

A couple of points here:

  1. Use the Select Class to work with the select and options tags.
  2. We should try to select an option only through Select type of object.
  3. Here is the code block for your reference :

    selectmonth = Select(driver.find_element_by_id('date_range_month_start'))
    for option in selectmonth.options:
        print(option.text)      
    

Update

If you face a ElementNotVisibleException due to style="width: 109px; display: none; use this block of code:

element = driver.find_element_by_id('date_range_month_start')   
driver.execute_script("return arguments[0].removeAttribute('style');", element)
selectmonth = Select(driver.find_element_by_id('date_range_month_start'))
for option in selectmonth.options:
    print(option.text)      

Upvotes: 1

Shadow
Shadow

Reputation: 9427

Selenium does that when an element is not visible on the screen.

You have display: none in your style tag. I think you'll find that if you remove it, then you will see what you expect.

I think this is because selenium is built to emulate user behaviour - and a user can not read text that is not shown.

Upvotes: 0

Related Questions