shalini shalini - 1 month ago 5
Python Question

Unable to select a value from a drop-down in selenium python

Im trying to select a value from dropdown :

<select name="ctl00$ContentPlaceHolder1$_ddl_sheet_name" id="ctl00_ContentPlaceHolder1__ddl_sheet_name">
<option selected="selected" value="0">--Select--</option>
<option value="tbl_E_RATES">E RATES</option>
<option value="tbl_F_RATES">F RATES</option>
<option value="tbl_B_RATES">B RATES</option>

</select>


But none of these commands are working

driver.find_element_by_css_selector("select#ctl00$ContentPlaceHolder1$_ddl_sheet_name > option[value='B_RATES']").click()

driver.find_element_by_xpath("//select[@id='ctl00_ContentPlaceHolder1__ddl_sheet_name']/option[text()='B RATES']").click()

driver.find_element_by_css_selector("select#ctl00_ContentPlaceHolder1__ddl_sheet_name > option[value='B_RATES']").click()


ERROR :-

NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//select[@id='ctl00_ContentPlaceHolder1__ddl_sheet_name']/option[text()='B RATES']"}

Answer

B_RATES is a link text of option but not it's value (value is tbl_B_RATES). Try this one:

driver.find_element_by_xpath('//select/option[text()="B RATES"]').click()

UPDATE

NoSuchElementException issue could be caused by page rendering completion delay. Try Explicit wait to wait until element is present on page:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, '//select/option[text()="B RATES"]'))).click()

UPDATE 2

Target drop-down menu located inside an iframe, so you need to switch to it first and then handle required elements:

driver.switch_to_frame(driver.find_element_by_xpath('//iframe[@src="http://rate.poultrybazaar.net/show_rates.aspx"]'))
driver.find_element_by_xpath('//select/option[text()="BROILER RATES (WEST BENGAL)"]').click() # Replace text with required value
driver.switch_to_default_content() # to quit from iframe