1

In Selenium, is there a way to get text from a dropdown menu and then put into a list in Python?

Suppose:

<select id="zoo">
    <option value="30">
    Lion
    </option>

    <option value="10">
    Elephant
    </option>

    <option value="5">
    Zebra
    </option>
</select>

How can I put Lion, Elephant, and Zebra into a list?

2 Answers 2

1

Use selenium.webdriver.support.select.Select() and get the .options:

options

Returns a list of all options belonging to this select tag

from selenium.webdriver.support.select import Select

select = Select(driver.find_element_by_id('zoo'))
print [option.text for option in select.options]

where driver is a webdriver instance.

DEMO (using this w3schools page (yeah, sorry for w3schools :)):

>>> from selenium import webdriver
>>> from selenium.webdriver.support.select import Select
>>> driver = webdriver.Firefox()
>>> driver.get('http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select')
>>> driver.switch_to.frame('view')
>>> select = Select(driver.find_element_by_tag_name('select'))
>>> [option.text for option in select.options]
[u'Volvo', u'Saab', u'Opel', u'Audi']

Note that select element on this page doesn't have an id, so I just find it using find_element_by_tag_name(). Also note that there are iframes there, so I have to switch to the appropriate iframe to be able to find the element.

Hope that helps.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a ton for your help. I do keep getting the same error however: TypeError: iteration over non-sequence Perhaps I'm not successfully finding the Select element?
@user2631667 you are welcome, can you show the code you are using and the full error traceback? Would help to help. Thanks.
0

here's what worked for me:

select = Select(driver.find_element_by_tag_name('select'))

text_list = []

for option in select.find_elements_by_tag_name('option'):
    text_list.append(option.text)

Thanks for the help!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.