I’m going to get the default selected value of the below dropdown
I wrote below code to do it.
Select selectyear = new Select(driver.findElement(By.id("year"))); WebElement year = selectyear.getFirstSelectedOption(); String selectedoption = year.getText();
But this throws the following error
org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been “select” but was “input”
How can I fix this? same code is working perfectly for dropdowns that don’t have “value” attribute.
Advertisement
Answer
The only explanation is there is another element with id year
, the input
tag.
Put this code before 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()); }
Solution is relative xpath for the select: select[@id='year']