Search code examples
pythonselenium-webdriverxpathselectdrop-down-menu

How to extract the text of the selected option of a Dropdown Menu using Selenium and Python


I'm trying to select the text of the menu option circled in the screen shot. In this case it's 'Age Harden'.

The best I can get is the selected value of 17043, not the text 'Age Harden'.

Here's what I've tried:

driver.find_element_by_xpath("//select[@id='lstOperation_Key']").get_attribute('text_content')

Returns None

driver.find_element_by_xpath("//select[@id='lstOperation_Key']").get_attribute('value')

Returns 17043

driver.find_element_by_xpath("//select[@id='lstOperation_Key']").get_attribute('text')

Returns None

driver.find_element_by_xpath("//select[@id='lstOperation_Key']").get_attribute('selected value')

Returns None

my_furnace_parameters_data['Furnace_Operation'] = driver.find_element_by_xpath("//select[@id='lstOperation_Key']//option[1]").get_attribute('text')

Returns 'Age Harden', BUT, when I test this on an operation that is not the 1st one on the list like 'Zoo Treatment' is it fails - it still returns 'Age Harden'.

enter image description here


Solution

  • first_selected_option

    first_selected_option() returns the first selected option in this select tag (or the currently selected option in a normal select).


    Seems you were pretty close. To extract the textContent of the default selected <option> you can use the first_selected_option property to identify the element and you can extract the option text as per the solution below:

    • Code Block:

      select = Select(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//select[@id='lstOperation_Key' and @name='lstOperation_Key']")))) //selecting tag
      element = select.first_selected_option
      print(element.text)
      # or
      print(element.get_attribute("innerHTML"))