I need to select an element from a drop-down menu.
For example:
As per the HTML provided:
To select an element from a html-select menu you have to use the Select Class. Moreover, as you have to interact with the drop-down-menu you have to induce WebDriverWait for the
element_to_be_clickable()
.
To select the with text as Mango from the dropdown you can use you can use either of the following Locator Strategies:
Using ID attribute and select_by_visible_text()
method:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "fruits01"))))
select.select_by_visible_text("Mango")
Using CSS-SELECTOR and select_by_value()
method:
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select.select[name='fruits']"))))
select.select_by_value("2")
Using XPATH and select_by_index()
method:
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "//select[@class='select' and @name='fruits']"))))
select.select_by_index(2)