Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get selected option using Selenium WebDriver with Java

I want to get the selected label or value of a drop down using Selenium WebDriver and then print it on the console.

I am able to select any value from the drop down, but I am not able to retrieve the selected value and print it:

Select select = new 
Select(driver.findElement(By.id("MyDropDown"))).selectByVisibleText(data[11].substring(1 , data[11].length()-1));
WebElement option = select.getFirstSelectedOption();

But all my efforts were in vain. How do I get the selected option?

like image 438
WomenInTech Avatar asked Aug 13 '12 13:08

WomenInTech


People also ask

How do you get the selected element from a dropdown in Selenium?

We can get a selected option in a dropdown in Selenium webdriver. The method getFirstSelectedOption() returns the selected option in the dropdown. Once the option is fetched we can apply getText() method to fetch the text.

Is selected method in Selenium Java?

isSelected() Method in SeleniumThe isSelected() method checks that if an element is selected on the web page or not. It returns a boolean value (true) if selected, else false for deselected. It can be executed only on a radio button, checkbox, and so on.

Is selected in Selenium Webdriver?

isSelected() This method is often used on radio buttons, checkboxes or options in a menu. It is used to determine is an element is selected. If the specified element is selected, the value returned is true. If not, the value returned is false.


3 Answers

You should be able to get the text using getText() (for the option element you got using getFirstSelectedOption()):

Select select = new Select(driver.findElement(By.xpath("//select")));
WebElement option = select.getFirstSelectedOption();
String defaultItem = option.getText();
System.out.println(defaultItem );
like image 174
Justin Ko Avatar answered Oct 22 '22 15:10

Justin Ko


Completing the answer:

String selectedOption = new Select(driver.findElement(By.xpath("Type the xpath of the drop-down element"))).getFirstSelectedOption().getText();

Assert.assertEquals("Please select any option...", selectedOption);
like image 19
Bhuvan Avatar answered Oct 22 '22 14:10

Bhuvan


In Selenium Python it is:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select

def get_selected_value_from_drop_down(self):
    try:
        select = Select(WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.ID, 'data_configuration_edit_data_object_tab_details_lb_use_for_match'))))
        return select.first_selected_option.get_attribute("value")
    except NoSuchElementException, e:
        print "Element not found "
        print e
like image 7
Riaz Ladhani Avatar answered Oct 22 '22 16:10

Riaz Ladhani