java - 如何使用随机选择获取列表中元素的文本?

标签 java selenium selenium-webdriver webdriver

我只是在寻找方法,它将帮助我使用 Java 上的 Selenium Webdriver 获取从下拉列表中随机选择的元素的文本值。

这是下拉列表的 HTML:

<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>

</select>

这是我的代码:

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.
    select.selectByIndex(option);
}

最佳答案

或者:

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

如果它是您想要的显示文本(在您的示例中似乎是相同的,但不一定是)。

关于java - 如何使用随机选择获取列表中元素的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35320821/

相关文章:

java - 基于时间的 Couchbase 查询

java - 如何确认swing是否安装

html - 识别文本出现次数最少的元素的正确 XPath 是什么?

javascript - 类型错误 : Cannot read property 'textToBePresentInElementValue' of undefined

xpath。如果兄弟值则选择元素

java - Play 2.5 : get response body in custom http action

java - onCreateView() 在第二次调用后没有显示从数据库中获取的任何数据

Selenium 无效元素状态: Element is not currently interactable and may not be manipulated

java - 在整个 selenium 套件中使用相同的网络驱动程序

selenium - 如何在 Selenium 测试中注入(inject) JS 函数?