如何使用Selenium测试选择span元素中的值?

时间:2012-12-21 01:07:19

标签: java selenium webdriver web-testing

我要测试的页面有一个span元素,实际上是一个下拉选择菜单。 “select”元素的Selenium代码不起作用,并引发以下内容:

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

该元素的代码如下所示:

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

打开下拉菜单时的代码是:

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

这是这样的:

The form with pseudo select element

编辑1:

这是我的Selenium代码:

            // 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();
        }

这是页面源代码查看此元素的方式:

enter image description here

如果需要,我可以添加更多详细信息。 感谢。

4 个答案:

答案 0 :(得分:4)

所以这就是发生的事情:

当您点击<div id="countSelect"></div>时,会执行JavaScript show_countSelector()并将值附加到表格中。那些“选择选项”实际上是“表格行”。

所以你的步骤是:
1)如果selec_option下的div类标识为countSelect,且标识为div,则需要先点击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()
2)之后单击特定行。

所以我将尝试展示Java代码(但是,我将Python用于Selenium):

{{1}}

像这样的东西。 :)

答案 1 :(得分:0)

您是否尝试过selectByValue("value")

答案 2 :(得分:0)

那是因为它不是select,即使它看起来像是......

你必须使用其他手段。我认为这很简单

element = driver.find(By.id("countVal"));
element.click()

应该有效

你必须找到选择工作的方式,应该有一些javascript涉及背后。当你知道元素的变化如何出现时,你将能够找到在Selenium中做什么。但那肯定不是纯粹的select

(注意:这是一个未经过测试的,甚至不是可编译的代码,但它会告诉你我如何看待这一点)

答案 3 :(得分:0)

您可以将Select class仅用于html原生选择...您使用自定义选择实际上是一个范围。

一个案例:

 public void selectValue(String item) {
    WebElement dropDown = driver.findElement(By.id("countTd"));
    dropDown.click();

    driver.findElement(By.xpath("//td[@id='countTd']/span[text()='" + item + "']")).click();
}