在这里,我尝试使用Selenium脚本从下拉列表中选择一个值,但 在控制台中却收到此错误,例如
“线程“主”中的异常” org.openqa.selenium.support.ui.UnexpectedTagNameException:元素应 为“选择”但为“跨度”。
public class HomeUserManagement { public static void main(String args[]) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\UMASHANKAR\\Documents\\selenuim\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.manage().window().maximize(); //for login driver.get("https://ecabportal.azurewebsites.net/dashboard"); driver.findElement(By.name("email")).sendKeys("abc@xyz.in"); driver.findElement(By.name("password")).sendKeys("abc123xyz"); driver.findElement(By.name("signIn")).click(); //actual code for selecting a value from dropdown driver.get("https://ecabportal.azurewebsites.net/user"); Select drpdwn=new Select(driver.findElement(By.id("select2-signup-username-container"))); drpdwn.selectByVisibleText("User Name"); drpdwn.selectByIndex(0);
下拉菜单中有多个值,我需要在其中选择一个值。
@MosheSlavin的分析和回答是正确的方向。
这个错误讯息…
"Exception in thread "main" org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been "select" but was "span"
…意味着您已经使用 Select 类与所需 元素进行交互,其中元素为 <span>.
Select
<span>
要使用硒从下拉列表中选择一个值,例如用户名,您可以使用以下解决方案:
driver.get("https://ecabportal.azurewebsites.net/dashboard"); new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.name("email"))).sendKeys("admin@malbork.in"); driver.findElement(By.name("password")).sendKeys("NsSaNj@0205"); driver.findElement(By.name("signIn")).click(); new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h1[contains(., 'Dashboard')]"))); driver.get("https://ecabportal.azurewebsites.net/user"); new WebDriverWait(driver, 20).until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//div[@id='load']"))); new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("span.select2-selection.select2-selection--single>span.select2-selection__rendered"))).click(); new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//span[@class='select2-results']//li[contains(., 'User Name')]"))).click();
Note:
elementToBeClickable()
click()
invisibilityOfElementLocated()