Reputation: 215
I'm trying to get all the option elements from the dropdown list and display the text of each option in the dropdown. But the text is not getting displayed. How to get the text for the options in the dropdown list?
This is what i have tried so far :
WebDriver d = new FirefoxDriver();
d.navigate().to("https://www.salesforce.com/form/signup/freetrial-sales.jsp?d=70130000000EqoP&internal=true");
Select s = new Select(d.findElement(By.id("CompanyEmployees")));
List<WebElement> options = s.getOptions();
for(WebElement option : options){
System.out.println(option.getAttribute("title"));
System.out.println(option.getText());
}
Here is the HTML:
<li class=" type-select">
<div class="control-container ">
<div class="label">
<span class="required-marker">*</span>
<label for="CompanyEmployees" id="CompanyEmployees_lbl">Employees</label>
</div>
<div class="field">
<select name="CompanyEmployees" id="CompanyEmployees">
<option value="">Employees</option>
<option value="3" title="1 - 5 employees">1 - 5 employees</option>
<option value="12" title="6 - 20 employees">6 - 20 employees</option>
<option value="50" title="21 - 100 employees">21 - 100 employees</option>
<option value="250" title="101 - 500 employees">101 - 500 employees</option>
<option value="2000" title="501 - 3,500 employees">501 - 3,500 employees</option>
<option value="3500" title="3,501+ employees">3,501+ employees</option>
</select>
</div>
<div class="info">
<label for="CompanyEmployees__c" id="CompanyEmployees_lel">Select the number of employees</label>
<img src="https://secure2.sfdcstatic.com/common/assets/images/error-icon.png" alt="" border="0">
</div>
</div></li>
Thanks in advance.
Upvotes: 0
Views: 1214
Reputation: 1730
Try:
List<WebElement> elements = driver.findElements(By.xpath("//select[@id='CompanyEmployees']//option"));
for (WebElement element : elements) {
element.getText();
}
Or:
WebElement yourSelect = driver.findElement(By.id("CompanyEmployees"));
List<WebElement> elements = new Select(yourSelect).getOptions();
for (WebElement element : elements) {
element.getText();
}
How to get select option text:
WebElement yourSelect = driver.findElement(By.id("CompanyEmployees"));
String text = new Select(yourSelect ).getFirstSelectedOption().getText();
Upvotes: 0
Reputation: 734
Use the following code
Select sel = new Select(element);
List<WebElement> list = sel.getOptions();
for(int i=0;i<list.size(); i++)
{
System.out.println(list.get(i).getText());
}
Also if possible post the html code. If the drop down does not contain select tag it is not possible to use select class.
Upvotes: 0
Reputation: 648
I used your code ans its working fine.I am able to see the text is getting printed on my console. Which webdriver version you are using? I checked it on version 2.38.
Upvotes: 0