Wanting to use Expected Conditions in Selenium to wait for an option in a dropdown to be selected.
One of the methods that can be used is element_located_selection_state_to_be(locator, isSelected)
However, I haven't been able to find an example of a locator
for the option that should be selected.
HTML:
<select id=mylist>
<option value="item1">First Item</option>
<option value="item2">Second Item</option>
<option value="item3">Third Item</option>
</select>
Python:
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
...
# 'browser' is the WebDriver
# find the dropdown box
dropdown = (
browser.find_element(
by=By.ID,
value='mylist'
)
)
# select the desired option
dropdown_select = Select(dropdown)
dropdown_select.select_by_value('item3')
# wait for option to become selected
WebDriverWait(browser, 10).until(
ec.element_selection_state_to_be(
dropdown_select, True # how do I 'locate' the option with value 'item3'???
)
)
Using dropdown_select
says expected type 'WebElement', got 'Select' instead
. This makes sense, as dropdown_select
is, of course, not a locator.
I could use something like the following...
selected_value = (
dropdown_select
.first_selected_option
.get_attribute('value')
)
if selected_value != 'item3':
raise ValueError('Selected values do not match')
But that's pretty hacky when a method is there for me to use.
How do I define a locator for an option within the Select?
Using xpath relative to the dropdown box, I can create a locator to the option I want like so:
desired_option = dropdown.find_element(
By.XPATH,
value='.//option[@value="item3"]'
)
Once I have the locator, I can create the wait
, using the element_selection_state_to_be()
method:
WebDriverWait(browser, 10).until(
ec.element_selection_state_to_be(desired_option, True)
)