如何使用Selenium从下拉列表中选择值?
鉴于下面是一段代码,表示下拉。 我需要在此下拉列表中选择日期值,表示为Date
---- Text Date Numeric Switch Map Location Marker Picker List
以下方法无效。
1.)使用选择导入org.openqa.selenium.support.ui.Select选择此值
Select elm = new Select(driver.findElement(By.xpath(".//*[@id='type']/option[3]"))); elm.selectByVisibleText("Date");
控制台显示:
元素应该是“选择”但是“选项”
2.)首先单击“下拉”以显示要选择的选项,然后单击该选项。
driver.findElement(By.xpath(".//*[@id='type']")).click(); driver.findElement(By.xpath(".//*[@id='type']/option[3]")).click();
控制台显示:
DEBUG元素缺少一个可访问的名称:id:type,tagName:SELECT,className:text-input ng-pristine ng-untouched ng-valid ng-scope
3.)使用JavascriptExecutor获取点击。
driver.findElement(By.xpath(".//*[@id='type']")).click(); ((JavascriptExecutor)driver).executeScript("arguments[0].click();", driver.findElement(By.xpath(".//*[@id='type']/option[3]")));
控制台显示:
DEBUG元素缺少一个可访问的名称:id:type,tagName:SELECT,className:text-input ng-pristine ng-untouched ng-valid ng-scope
4.)使用鼠标hover选项在下拉列表中选择,然后单击它。
driver.findElement(By.xpath(".//*[@id='type']")).click(); WebElement subdrop = driver.findElement(By.xpath(".//*[@id='type']/option[3]")); Actions action = new Actions(drive); action.moveToElement(subdrop).perform(); Custom.Twait(); action.click(subdrop).perform();
控制台显示:
线程“main”中的exceptionorg.openqa.selenium.UnsupportedCommandException:POST / session / a37a745a-e40c-45a9-9760-8e01b451a017 / moveto与已知命令不匹配(警告:服务器未提供任何堆栈跟踪信息)
我还添加了Wait in Between我正在使用此代码。 为简单起见,我没有包含它。
需要帮忙。
在你的第一个选项selenium中明确指出Element应该是“select”但是是“option” ,这意味着你在提供xpath
for option
而期望只有xpath
for select。
不需要使用您提供的其他选项,只需使用您的第一个选项如下: –
Select elm = new Select(driver.findElement(By.id("type"))); elm.selectByVisibleText("Date");
或ByIndex
elm.selectByIndex(2);
或ByValue
elm.selectByValue("1");
如果您的第一个选项不幸地不起作用,我希望您使用第三个选项使用JavascriptExecutor
如下: –
WebElement select = driver.findElement(By.id("type")); ((JavascriptExecutor)driver).executeScript("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", select, "Date");
希望它会帮助你...... 🙂