如何使用 Java 在 Selenium WebDriver 中选择下拉值 [英] How to select a dropdown value in Selenium WebDriver using Java
问题描述
我是 selenium 的新手,目前正在研究 selenium webdriver 我想从下拉列表中选择一个值.id=periodId 和选项很多,因为我试图选择过去 52 周.
I am new to selenium , currently am working on selenium webdriver i want to select a value from the drop down. The id=periodId and the option is many in that am trying to select Last 52 weeks.
这是HTML代码:
<select id="periodId" name="period" style="display: none;">
<option value="l4w">Last 4 Weeks</option>
<option value="l52w">Last 52 Weeks</option>
<option value="daterange">Date Range</option>
<option value="weekrange">Week Range</option>
<option selected="" value="monthrange">Month Range</option>
<option value="yeartodate">Year To Date</option>
</select>
请给我一些点击下拉菜单的方法.
Please suggest me some ways to click the drop down.
我尝试使用上述示例行,但出现错误,例如 Element 当前不可见,因此可能无法与之交互命令持续时间或超时:32 毫秒下拉值是 jquery 多选小部件格式.
I tried with the above example lines but am getting error such as Element is not currently visible and so may not be interacted with Command duration or timeout: 32 milliseconds the drop downs values are the jquery multiselect widget format.
推荐答案
只需将您的 WebElement 包装到 Select Object 中,如下所示
Just wrap your WebElement into Select Object as shown below
Select dropdown = new Select(driver.findElement(By.id("identifier")));
完成此操作后,您可以通过 3 种方式选择所需的值.考虑这样的 HTML 文件
Once this is done you can select the required value in 3 ways. Consider an HTML file like this
<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>
现在识别下拉菜单
Select dropdown = new Select(driver.findElement(By.id("designation")));
要选择它的选项,请说程序员",您可以这样做
To select its option say 'Programmer' you can do
dropdown.selectByVisibleText("程序员");
或
dropdown.selectByIndex(1);
或
dropdown.selectByValue("prog");
这篇关于如何使用 Java 在 Selenium WebDriver 中选择下拉值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!