[英]Selecting value from <li> dropdown - Selenium
I'm trying to select a value from a small dropdown that appears to be a "ul" Here's what I see in Firebug: 我试图从一个似乎是“ul”的小下拉列表中选择一个值这是我在Firebug中看到的:
<button class="btn btn-default dropdown-toggle" aria-expanded="true" aria-haspopup="true" data-toggle="dropdown" type="button">
<ul class="dropdown-menu">
<li>
<a href="javascript:void(0)">1</a>
</li>
<li>
<a href="javascript:void(0)">2</a>
</li>
<li>
<a href="javascript:void(0)">3</a>
Here's what I have so far, in Java: 以下是我到目前为止用Java编写的内容:
public void selectPhoneType(String option)
{
driver.findElement(By.className("caret")).click();
new WebDriverWait(driver, 5).until(ExpectedConditions.visibilityOfElementLocated(By.className("dropdown-menu")));
WebElement element = driver.findElement()
}
Let's say I wanted to select/click on option "1" . 假设我想选择/点击选项“1” 。 How would I complete my code? 我如何完成我的代码? I haven't worked with "li" too much so I tried using a select, which obviously didnt work. 我没有太多使用“li”,所以我尝试使用select,这显然没有用。 Any help would be appreciated! 任何帮助,将不胜感激! Thanks 谢谢
Try something like this: 尝试这样的事情:
public void selectPhoneType(String option) {
// Open the dropdown so the options are visible
driver.findElement(By.className("dropdown-menu")).click();
// Get all of the options
List<WebElement> options = driver.findElements(By.xpath("//ul[@class='dropdown-menu']/li"));
// Loop through the options and select the one that matches
for (WebElement opt : options) {
if (opt.getText().equals(option)) {
opt.click();
return;
}
}
throw new NoSuchElementException("Can't find " + option + " in dropdown");
}
Note: Selenium's Select() won't work here because your list is not under a 'select' tag. 注意:Selenium的Select()在这里不起作用,因为你的列表不在'select'标签下。
Based on how it's selected in the application you either should simulate mouse click with element.click()
or simulate keydown/keyup event with element.sendKeys(Keys.ENTER);
根据它在应用程序中的选择方式,您应该使用element.click()
模拟鼠标单击,或者使用element.sendKeys(Keys.ENTER);
模拟keydown / keyup事件element.sendKeys(Keys.ENTER);
Also be aware that touch events may handle differently by your application (click may not work) Here's a similar question 另请注意,触摸事件可能会因您的应用程序而有所不同(单击可能不起作用) 这是一个类似的问题
driver.FindElement(By.XPath("//ul[@class='dropdown-menu']/li/a")).Click();
Another approach which parameterizes the selector. 另一种参数化选择器的方法。
This returns all 3 options: 这将返回所有3个选项:
$$("ul.dropdown-menu>li:eq a")
This adds a parameter to select which in the list you want: 这会添加一个参数来选择列表中您想要的内容:
$$("ul.dropdown-menu>li:nth-child(1) a")
Then you can map for your tests the child number and pass it into the selector: 然后,您可以将您的测试映射到子编号并将其传递到选择器:
1 = whatever
2 = whatever
3 = whatever
public void By someDroplist(String selection)
{
return By.cssSelector("ul.dropdown-menu>li:nth-child(" + selection + ") a");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.