如何选择下拉选项

时间:2018-03-13 01:18:01

标签: java selenium selenium-webdriver

我想使用Selenium找到以下下拉选项,但我无法这样做。

<div class="customFonts" style="">
  <div class="fontOptions"><div class="fontView">
    <div class="fontDropDown">
      <div class="styledSelect customSelect">
        <select style="opacity: 0;">
          <option value="Arial">Arial</option>
          <option value="courier, monospace">Courier</option>
          <option value="Geneva">Geneva</option>
          <div class="toggleSwitchSliderInner">
            <img src="images/toggle_circle.png" style="display: block; right: -3px;">
          </div>
          <option value="Helvetica">Helvetica</option><!--This option-->
          <option value="Roboto">Roboto</option>
          <option value="sans-serif">sans-serif</option>
          <option value="sourceSansPro">SourceSansPro</option>
          <option value="times new roman, serif">Times New Roman</option>
          <option value="verdana, sans-serif">Verdana</option>
        </select>
        <span>Courier</span>
        <div class="customSelectIcon"></div>
      </div>
    </div>

如何选择以下下拉选项。我一直无法找到元素。请建议

我尝试了以下两种变体:

List<WebElement> b = driver.findElements(
    By.xpath("//div[@class='fontDropDown']"));
new Select(b.get(1).findElement(
    By.xpath("//select[text()='Helvetica']")));

抛出元素无法找到。和

List<WebElement> b = driver.findElements(
    By.xpath("//div[@class='fontDropDown']"));
new Select(b.get(1).findElement(
    By.xpath("//select/option[text()='Helvetica']")))
产生元素的

应该是select但是option

1 个答案:

答案 0 :(得分:1)

您的第一种方法找不到元素,因为该值位于选项内,而不是选择元素内。

您的第二种方法更好,但您尝试将结果包装在Select中。这不起作用,因为该方法返回选项字段的句柄。因此,请不要将WebElement包裹起来,将其转换为Select

WebElement option = b.get(1).findElement(
    By.xpath("//select/option[text()='Helvetica']"));

由于您希望选择此选项,您应该专注于访问Select元素,然后使用其方法选择其中一个选项。因此,请查看Select的{​​{3}}。

以下是两种变体:

Select select = new Select(b.get(1).findElement(By.tagName("select")));

// Select by value (the attribute)
select.selectByValue("Helvetica");

// Select by visible text (the text inside the tag)
select.selectByVisibleText("Helvetica");
相关问题