如何解决 "org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "input"" selenium 错误

How to solve "org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "input"" selenium error

我将获取以下下拉菜单的默认 selected 值

我写了下面的代码来做到这一点。

Select selectyear = new Select(driver.findElement(By.id("year")));
WebElement year = selectyear.getFirstSelectedOption();
String selectedoption = year.getText();

但这会引发以下错误

org.openqa.selenium.support.ui.UnexpectedTagNameException: 元素应该是“select”但是是“input”

我该如何解决这个问题?相同的代码对于没有“值”属性的下拉菜单非常有效。

唯一的解释是还有另一个元素的 ID 为 year,即 input 标签。

将此代码放在 Select selectyear = new Select(driver.findElement(By.id("year"))); 之前:

List<WebElement> elements = driver.findElements(By.id("year"));
        for (WebElement element: elements) {
            System.out.println("Tag: " + element.getTagName());
            System.out.println("Text: " + element.getText());
            System.out.println("Location: " + element.getLocation());
        }

解决方案是 select 的相对 xpath:select[@id='year']