The currently recommended method of selecting an item from a dropdown menu is to use the Select class. Here’s a quick example:
from selenium.webdriver.support.ui import Select
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("file:///C:\testing\\test.html")
element = browser.find_element_by_id("id_country")
select = Select(element)
select.select_by_visible_text("Armenia")
However, the HTML you posted doesn’t seem to work; I just get an empty dropdown box. You’ll need to fix that in order to be able to use the above code. For example:
<html><body>
<select id="id_country" name="country">
<option>Select Your Country</option>
<option>Afghanistan</option>
<option>Armenia</option>
</select>
</body></html>
This works fine for me, producing a dropdown box with three options – Select Your Country
, Afghanistan
and Armenia
. Pointing the above Python script at this file correctly selects Armenia
.
Edit: Here’s a quick-and-dirty Python script that successfully selects Armenia from the list of countries:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get("http://ds.arm.com/rfq/")
country = "Armenia"
dropdown_path = "id('content')/form/fieldset/div[5]/div[2]/div/a[2]"
country_path = "id('content')/form/fieldset/div[5]/div[2]/div/ul/li[contains(text(), '%s')]" % country
browser.find_element_by_xpath(dropdown_path).click()
browser.find_element_by_xpath(country_path).click()
It makes use of XPaths to locate the dropdown arrow and then the <li>
tag containing “Armenia”. I don’t claim that it’s especially intuitive, or neat to look at, but it works. They’ve really over-complicated things with that website, so I’m not sure if the simpler Select
method can be made to work here. In general, if you can locate an element using an id (find_element_by_id
), class (find_element_by_class
) or name (find_element_by_name
), you should do so. None of those work here, unfortunately 🙂
I can recommend the XPath Checker extension for Firefox to help you find similar XPaths for the other form elements. Good luck, I really don’t envy you having to work with that site!!
16
solved how to select custom dropdown list element from selenium