java - 如何使用 Selenium 测试在 span 元素中选择值?

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

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

最佳答案

所以这是正在发生的事情:

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

所以你的步骤是:
1) 如果没有类为 selec_option 的行在 div 下ID countSelect , 然后你需要点击那个 div首先。
2) 然后点击特定的行。

所以我将尝试展示 Java 代码(但是,我将 Python 用于 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()

是这样的。 :)

关于java - 如何使用 Selenium 测试在 span 元素中选择值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13982935/

相关文章:

java - 当 Selenium2 findElement 失败时故障转移到 JavascriptExecutor?

javascript - 如何通过javascript函数获取当前web元素的clientHeight和scrollHeight?

java - 将 JVM 嵌入到 C++ 应用程序中 : How to link it properly?

java - 如何解决我的自动化代码中的错误?

Java : When to skip null checks on an object?

jquery - 找到 WebDriver 元素,但单击不返回任何内容

python - 全局名称 'wd' 未在 Python 中定义

c# - 在 .NET 中禁用 ChromeDriver 扩展

加密 token 的 Java PKCS11 标准

java - 验证静态外部类的私有(private)静态嵌套类的非静态方法的调用