2

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.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
alexcode02
  • 23
  • 3
  • You can find the working solution here : https://stackoverflow.com/questions/11934966/how-to-get-selected-option-using-selenium-webdriver-with-java . Refer to the Python solution. – Srinivasu Kaki Feb 18 '23 at 17:17
  • Does this answer your question? [How to get selected option using Selenium WebDriver with Java](https://stackoverflow.com/questions/11934966/how-to-get-selected-option-using-selenium-webdriver-with-java) – Srinivasu Kaki Feb 18 '23 at 17:18

2 Answers2

1

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
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

you can use regular get_attribute() function

select = Select(driver.find_element(By.CSS_SELECTOR, "yout_selector"))
select.select_by_visible_text("visible_text")
selected_option = select.first_selected_option
option_value = selected_option.get_attribute("value")
print("Value of selected option is:" + option_value )

first_selected_option propert convert item into Webelement. so, you can use regular Webelement functions to do any operation you want.

Mahsum Akbas
  • 1,523
  • 3
  • 21
  • 38