0
votes

I have the following snippet of code for combo box/drop down:

<select id="color">
<option value="">Select color</option>
<option value="1">Blue</option>
<option value="2">Green</option>
<option value="3">Red</option>

If I select Blue then Blue is displayed in a combo/drop down. I would like to get the text between the tags using Selenium 2 (WebDriver) using Java for checking against the selected value displayed in the combo box. How can I get the text from the selected value of the combo box?

2

2 Answers

1
votes

Try this:

select.getFirstSelectedOption().getText();

or

select.getFirstSelectedOption().getAttribute("your attribute");
1
votes

To find all the values of selector of the options:

String css1 ="select[id='color'] option[value='']"
String css2 ="select[id='color'] option[value='1']"
String css3 ="select[id='color'] option[value='2']"
String css4 ="select[id='color'] option[value='3']"

1st way: as Tarken mentioned above:

driver.findElement(By.cssSelector(css1)).getText().trim();

2nd way using JS:

String getTextByjs(String css) {
JavascriptExecutor js = (JavascriptExecutor) driver;
        StringBuilder stringBuilder = new StringBuilder();

stringBuilder.append("var x = $(\""+css+"\");");
        stringBuilder.append("return x.text().toString();")       ;


       String res= (String) js.executeScript(stringBuilder.toString());
return res;

}
getTextByjs(String css1)