使用Selenium和Java获取菜单列表时遭遇UnexpectedTagNameException异常:元素应为select却为a
Hey there, let's break down and fix this issue for you!
错误原因分析
The UnexpectedTagNameException you're seeing happens because you're trying to use Selenium's Select class on an <a> (anchor) tag—but Select is exclusively designed to work with HTML <select> dropdown elements. When the class checks the element's tag and finds it's not select, it throws this exact error.
Looking at your code, the element you're targeting (//*[@id="logo-menu"]/div/div[1]/div/a) is a menu trigger link, not a dropdown select box. Clicking this link expands a navigation menu, which is what you actually want to scrape options from.
修正后的代码实现
Here's the adjusted code that will correctly expand the menu and fetch all its options:
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions; import java.util.List; import java.util.concurrent.TimeUnit; public static void main(String[] args) { // Set ChromeDriver path System.setProperty("webdriver.chrome.driver", "D:\\selenium files\\chromedriver_win32_new\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); try { driver.manage().window().maximize(); driver.get("https://www.tutorialspoint.com/tutor_connect/index.php"); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Click the menu trigger to expand the navigation menu WebElement menuTrigger = driver.findElement(By.xpath("//*[@id=\"logo-menu\"]/div/div[1]/div/a")); menuTrigger.click(); // Use explicit wait to ensure menu options are visible (more reliable than implicit wait) WebDriverWait wait = new WebDriverWait(driver, 10); List<WebElement> menuOptions = wait.until( ExpectedConditions.visibilityOfAllElementsLocatedBy( By.xpath("//*[@id=\"logo-menu\"]/div/div[1]/div/div/a") ) ); // Loop through and print each menu option text for (WebElement option : menuOptions) { String optionText = option.getText(); if (!optionText.isEmpty()) { // Skip empty elements if any System.out.println(optionText); } } } finally { // Always close the driver to clean up resources driver.quit(); } }
关键说明
- Remove the
Selectclass: Since this isn't a<select>dropdown, we don't need it. Instead, we first click the menu trigger to reveal the options. - Explicit Wait: Using
WebDriverWaitensures we only try to access the menu options once they're fully visible, which avoidsNoSuchElementExceptionthat might happen if the menu takes a moment to load. - Cleanup: Added a
finallyblock to ensure the driver is always closed, even if an error occurs.
内容的提问来源于stack exchange,提问作者Prashant Kumar

