首页 > 解决方案 > 如何单击下拉菜单并通过 Selenium 和 Java 选择一个选项?

问题描述

我正在尝试单击下拉按钮,代码运行成功,但未在 selenium 中单击下拉按钮。

<select id="comp_drpdwn" data-select-id="f41d68e6-38b3-19cc-c392-3c9fc33690e8" class="initialized">
   <option value="0">Select Company</option>
   <option value="Acme~54sc234xb">Acme</option>
   <option value="Acme Bar &amp; Grill~TI17267302">Acme Bar &amp; Grill</option>
   <option value="Ball &amp; Chain~TI58377308">Ball &amp; Chain</option>

我的代码是:

WebElement element = driver.findElement(By.xpath(".//*[@id='comp_drpdwn']"));
Actions actions = new Actions(driver);
actions.moveToElement(element).click().build().perform();

标签: javaseleniumselenium-webdriverdrop-down-menuwebdriver

解决方案


这应该有效:

WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[@id='comp_drpdwn']"))); 
Select select = new Select(element);
select.selectByVisibleText("Acme");

推荐阅读