How to select value in a span element with Selenium testing?

vlr picture vlr · Dec 21, 2012 · Viewed 35.3k times · Source

The page I am trying to test has a span element that is actually functioning as a drop down select menu. The Selenium code for "select" elements does not work and throws the following:

Exception in thread "main" org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "span"

The code for that element looks as the following:

<span style="width: 100%" val="30" id="countVal">30</span>

The code when I open the drop down menu is:

<tr onclick="selectNewCount(1);" class="selec_option">
<td onmouseout="blankit(this)" onmouseover="colorit(this)" class="bones_pointer out_color" id="tdgroup1">50</td>
</tr>

This is how this looks like:

The form with pseudo select element

EDIT 1:

This is my Selenium code:

            // choose number of records.
        try {
            WebDriverWait wait = new WebDriverWait(driver, /*seconds=*/10);

            element = wait.until(presenceOfElementLocated(By.id("countVal")));

            Select select = new Select(element);
            select.deselectAll();
            select.selectByVisibleText("100");

        } catch (NoSuchElementException ex) {
            System.out.println("PAGE SOURCE: \n" + driver.getPageSource());
            ex.printStackTrace();
        }

This is how page source code looks around this element:

enter image description here

I can add more details if required. Thanks.

Answer

Alex Okrushko picture Alex Okrushko · Dec 21, 2012

So here is what's happening:

When you click on <div id="countSelect"></div> JavaScript's show_countSelector() is executed and the values are appended to the table. Those "select options" are actually "table rows".

So your steps are:
1) If there are no rows with class selec_option under div with id countSelect, then you need to click on that div first.
2) After that you click on the particular row.

So I'll try to show the Java code (however, I use Python for Selenium):

WebElement selectorElement = driver.find(By.xpath('//*[@id="countSelect"]')));

WebElement elementOfInterest;
try {
    //trying to get the "select option"
    elementOfInterest = selectorElement.findElement(By.xpath('//*[contains(@class,"selec_option")]/td[@text()="50"]'))

} catch (NoSuchElementException e) { 
    //so options are not visible, meaning we need to click first
    selectorElement.click()
    //good idea would be to put "wait for element" here
    elementOfInterest = selectorElement.findElement(By.xpath('//*[contains(@class,"selec_option")]/td[@text()="50"]'))
}
//this would select the option
elementOfInterest.click()

Something like this. :)