如何使用selenium

时间:2016-09-03 22:18:44

标签: java selenium

我是编程并尝试使用selenium webdriver自动化场景的新手。我有这个场景,我需要下面的代码,我想从下拉列表中选择一件T恤尺码。有人可以指导我如何做到这一点?

我尝试使用selectwithIndex,selectwithvisisbletext等选项。但在这种情况下,我首先需要检查可用的大小,然后从下拉列表中选择一个。

<div class="dbk-select dbk-select_full">
<select class="dbk-form--input">`enter code here`
  <option value="true" disabled="" style="display: none;">Select Size</option>
  <option value="false" data-value="479804001088140">140</option>
  <option value="false" data-value="479804001088152">152</option>
  <option value="false" data-value="479804001088164">164</option>
  <option value="false" data-value="479804001088176">176 (out of stock)</Option>
</select>

1 个答案:

答案 0 :(得分:0)

如果您想根据可用性从下拉列表中选择一个选项,那么您可以尝试下面的代码段

/**
 * Call this method with expected size to select and with the drop down
 * element By locator
 *
 * @param expectedSize     the size which needs to select from drop down
 * @param by               By locator to find select web element
 * @return                 if the expected option selected then returns true
 */
public static boolean selectByText(String expectedSize, By by) {
       boolean isExpectedSizeSelected = false;
       WebElement dropdownElement = driver.findElement(by);
       Select dropdown = new Select(dropdownElement);
       List dropdownOptions = dropdown.getOptions();
       for(WebElement option : dropdownOptions) {
             // Condition to validate option element is not null 
             if(option != null) {
               String actualSize = option.getText();
               if(actualSize == expectedSize) && !expectedSize.contains("out of stock")) {
                   dropdown.selectByVisibleText(actualText);
                   isExpectedSizeSelected = true;
               }
             }
       }
       return isExpectedSizeSelected;
}