Reputation: 23
I was testing my code over: https://semantic-ui.com/modules/dropdown.html
I wrote the following code in Python3 which finds all drop-downs in a given webpage and selects the last option for each drop-down:
dropdowns = driver.find_elements(By.XPATH, '//select[@class="ui dropdown"]')
print(str(len(form_dropdowns)))
for drop_down in form_dropdowns:
driver.execute_script("arguments[0].click();", drop_down)
options = drop_down.find_elements(by=By.TAG_NAME, value='option')
print(str(len(options)))
driver.execute_script("arguments[0].click();", options[len(options) - 1])
time.sleep(100)
I see the following printed on screen:
2
3
3
Which means 2 drop-downs were found, both with 3 options to select from.
BUT I don't see any value being changed in the UI, why is that?
Upvotes: 1
Views: 106
Reputation: 193078
Although it seems OP's approach to select the last option using the following line of code is working,
driver.execute_script("arguments[0].click();", options[len(options) - 1])
I'm totally against the idea of selecting the last option.
Ideally to interact with any html-select element we must be using the Select()
class and use either among the option index, option value or option text to choose the desired <option>
.
As an example,
Using select_by_value()
:
Select(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "xpath_select_element")))).select_by_value("value")
Using select_by_visible_text()
:
Select(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "xpath_select_element")))).select_by_visible_text("text")
Note : You have to add the following imports :
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
You can find a couple of relevant detailed discussions in:
Upvotes: 1