crymeariver crymeariver - 1 year ago 75
Java Question

How can i get text of the element in the list, using random select?

I'm just looking for the method, that will help me to get text value of the element selected randomly from the dropdown list using Selenium Webdriver on Java.

Here is HTML of the dropdown list:

<select name="ctl00$ctl00$ContentPlaceHolder1$cphContentLeft$ddlCabinType" id="ctl00_ctl00_ContentPlaceHolder1_cphContentLeft_ddlCabinType" class="ddlWidth form-control" onchange="BookOnline.onCabinTypeChange();" style="margin-top: 4px;">
<option value="0"> Please Select </option>
<option value="Inside">Inside</option>
<option selected="selected" value="Outside">Outside</option>
<option value="Balcony">Balcony</option>
<option value="Suite">Suite</option>


Here is my code:

public void selectRandomValue() {
Select select = new Select(getWebElement());
List<WebElement> weblist = select.getOptions();
int options = weblist.size();
Random random = new Random();
int option = random.nextInt(options);
String value = Integer.toString(option);
logMessage("Select random " + value + " value in"); // In logMessage i want to recieve text instead of number.

Answer Source


String value = weblist.get(option).getText();

if it's the displayed text you want (which seems to be the same in your example, but which doesn't have to be).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download