Spartica
Spartica

Reputation: 33

Using a select-box with Selenium

I am trying to find a suitable way for Selenium to select an item within a select-box.

I have tried using:

new Select(driver.findElement(By.xpath("//select-box[@name='countryCode']"))).selectByVisibleText(country);

but get the expected error of:

org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "select-box"

Trying to use WebElement works great to select the element, but not able to "search" the results for the correct item list.

This is the HTML I am working with that I have simplified a bit:

<select-box name="type" options="$ctrl.ClubTypes"
  track-by="value" label-by="label" required="">
  <div class="SelectBox">
    <div>
      <div></div>
      <input readonly="" class="Input " type="text" value="Club">
    </div>
    <ul class="SelectBox-options ng-scope" ng-if="$ctrl.isShowingOptions" style="">
      <li>Country list items</li> 
    </ul>
  </div>
</select-box>

I am fairly new to using Selenium and programming in general so any help would be fantastic.

Upvotes: 0

Views: 292

Answers (2)

cruisepandey
cruisepandey

Reputation: 29362

This exception

org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "select-box"

basically means is, that you are trying to use Select class from Selenium, (which is solely meant for drop downs built using Select and option tag).

If you pay attention to the HTML that you have shared, There isn't any Select Instead it is select-box

Solution :

  1. Try to click on drop down first, then once options are visible click directly to the desired options as well.

Code trial 1 :

Thread.sleep(5);
driver.findElement(By.xpath("//select-box[@name='countryCode']")).click();

Code trial 2 :

new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//select-box[@name='countryCode']"))).click();

use any one of them and it would click on drop down, and then you can select your desired option in similar way.

I would need to see the outerHTML first to find the reliable locator to click on option.

Upvotes: 1

Hana Bzh
Hana Bzh

Reputation: 2260

Instead of

new Select(driver.findElement(By.xpath("//select-box[@name='countryCode']"))).selectByVisibleText(country);

Just try

String contry = "IRAN";
    
driver.findElement(By.xpath("//div[@class='SelectBox']")).findElement(By.xpath(".//li[contains(text(),'" + country + "')]"))

Upvotes: 1

Related Questions