Search code examples
pythonselenium-webdriverdrop-down-menuautomated-testshtml-select

How to get the value attribute of the selected option in a dropdown using selenium with python?


I have a selenium code (using python) that select a value in a dropdown using the select_by_value method of the 'Select' package in selenium.

Picture of html code

As you can see in the picture, I input the value 1 in the code and it selects "Poste" which is the text associated with the value 1.

My question is if there is a way to get the value that was selected after the select process.

I know that with the first_selected_option method I can go get the text of the option selected with :

selected_value = options_com.first_selected_option
sv = selected_value.text
print(sv)

So is there a way to return the value selected, in this exemple the value = "1", instead of the text.


Solution

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


    Solution

    To print the value of the value attribute of the selected option you can use the get_attribute() method as follows:

    select = Select(driver.find_element(By.XPATH, "//select[@id='client.select.communication']))
    select.select_by_value("1")
    print(select.first_selected_option.get_attribute("value")) # prints -> 1
      
    

    Note : You have to add the following imports :

    from selenium.webdriver.common.by import By