41 java selenium webdriver selenium-webdriver
如何使用带有Java的Selenium WebDriver从性别下拉列表中选择项目(例如男性,女性)?
我试过这个
WebElement select = driver.findElement(By.id("gender"));
List<WebElement> options = select.findElements(By.tagName("Male"));
for (WebElement option : options) {
if("Germany".equals(option.getText()))
option.click();
}
Run Code Online (Sandbox Code Playgroud)
我上面的代码不起作用.
som*_*guy 43
使用 -
new Select(driver.findElement(By.id("gender"))).selectByVisibleText("Germany");
Run Code Online (Sandbox Code Playgroud)
当然,你需要 import org.openqa.selenium.support.ui.Select;
Abh*_*ngh 21
只需将WebElement包装到Select Object中,如下所示
Select dropdown = new Select(driver.findElement(By.id("identifier")));
Run Code Online (Sandbox Code Playgroud)
完成此操作后,您可以通过3种方式选择所需的值.考虑像这样的HTML文件
<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>
Run Code Online (Sandbox Code Playgroud)
现在要确定下拉列表了吗
Select dropdown = new Select(driver.findElement(By.id("designation")));
Run Code Online (Sandbox Code Playgroud)
要选择其选项,请说"程序员",您可以这样做
dropdown.selectByVisibleText("Programmer ");
Run Code Online (Sandbox Code Playgroud)
要么
dropdown.selectByIndex(1);
Run Code Online (Sandbox Code Playgroud)
要么
dropdown.selectByValue("prog");
Run Code Online (Sandbox Code Playgroud)
快乐编码:)
小智 5
您应该提到的标记名称就像"选项"一样,如果带有空格的文本我们可以使用此方法它应该可以工作.
WebElement select = driver.findElement(By.id("gender"));
List<WebElement> options = select.findElements(By.tagName("option"));
for (WebElement option : options) {
if("Germany".equals(option.getText().trim()))
option.click();
}
Run Code Online (Sandbox Code Playgroud)
Google“选择项目selenium webdriver”显示How do I set an option as selected using Selenium WebDriver (selenium 2.0) client in ruby作为第一个结果。这不是 Java,但您应该能够无需太多工作就可以翻译它。https://sqa.stackexchange.com/questions/1355/what-is-the- Correct-way-to-select-an-option-using-seleniums-python-webdriver 位于前 5 名,同样不是 Java,而是API 非常相似。
| 归档时间: |
|
| 查看次数: |
299525 次 |
| 最近记录: |