Bob Jones
Bob Jones

Reputation: 171

How do I select the drop down option

I want to locate the following drop-down option using Selenium, but I'm unable to do so.

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

How do I select the following drop down option. I keep getting element cannot be located. Please suggest

I tried the following two variants:

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

which throws element cannot be located. And

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

which yields element should have been select but was option.

Upvotes: 1

Views: 163

Answers (1)

Zabuzard
Zabuzard

Reputation: 25903

Your first approach doesn't locate the element since the value is inside the option, not inside the select element.

Your second approach is better, but you try to wrap the result in a Select. This does not work, since the method returns a handle to the option field. Therefore, convert it to a WebElement by not wrapping a Select around:

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

Since you want to select this option, you should actually focus on accessing the Select element and then using its methods to select one of the options. Therefore, take a look at the documentation of Select.

Here are two variants:

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");

Upvotes: 1

Related Questions