ENPM ENPM - 1 year ago 90
HTML Question

Error when getting options of Select element in Python Selenium

I am trying to list the possible options in this Select element.

<select id="sl_coursePage" onchange="document.frm.submit();" name="sl_coursePage">
<option selected="selected" value="0"></option>
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
<option value="4"></option>
<option value="5"></option>
<option value="6"></option>
<option value="7"></option>
<option value="8"></option>
<option value="9"></option>
<option value="10"></option>

I can find the element itself fine with
elem = driver.get_element_by_name('sl_coursePage')
, but then when I tried to list the options by using
, it gives me empty lists.

So then I tried to use
and get the list by the following code:

elem = driver.get_element_by_name('sl_coursePage')
select = Select(elem)
list = select.options

However, when I try this, it raises this error:

selenium.common.exceptions.UnexpectedTagNameException: Message: Select only works on <select> elements, not on <input>

I don't understand how this is not a Select element when its tags say "select". If anyone can get any of these methods to work or present a functioning alternative method, I would be extremely grateful. Thanks in advance.

Answer Source

It looks like there is an another element with the same name which is not select and get matched by the "by name" locator. Improve the way you locating the element explicitly asking for select element with the desired name:

elem = driver.find_element_by_css_selector('select[name=sl_coursePage]')

Or, checking the id:

elem = driver.find_element_by_css_selector('select#sl_coursePage')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download