如何使用android web driver选择select标签的任何选项

时间:2012-09-12 03:23:36

标签: android selenium webdriver

我正在为Android设备的网站编写测试用例。我需要从页面的下拉列表中选择一个选项。但似乎android web驱动程序没有提供任何解决方案。

我尝试了Select API,但它无效。

代码段

      Select loginType = new Select(this.driver.findElement(By.xpath(LOGIN_TYPE_CHOICE)));
      loginType.selectByValue("smartphone");
      driver.findElement(By.id(LOGIN_BUTTON)).click();

寻找一些解决方法。

3 个答案:

答案 0 :(得分:3)

我正在使用c#对android,firefox Chrome和IE运行selenium测试,我遇到了与android驱动程序相同的问题。

这对我有用:(如果根据Java约定重构代码,它应该在java中工作)

string jsToBeExecuted="document.getElementById('<insert dropdown Id here>').selectedIndex=<insert index here>";

IJavaScriptExecutor jsExecutor = (IJavaScriptExecutor)this.Driver;
jsExecutor.ExecuteScript(jsToBeExecuted);

请注意,屏幕上不会显示任何更改! ! !

在提交具有所选索引的元素时将被使用。 如果你想对它添加一些调整来按文字或任何你喜欢的方式选择元素,这取决于你。

答案 1 :(得分:0)

我从使用selenium的自动化Web应用程序的到期中得到以下假设。 正如我所知,selenium无法与下拉选项进行交互,因为它们被认为是不可见的(不活动的)。 它始终有效的方式 - 就是使用js。 首先使用css选择器正确定位元素并使用firepath验证它(在ffox中添加到firebug) enter image description here

所以你得到了css sselector:

String css=....;
public void jsClickByCss(String cssLocator){
JavascriptExecutor js = (JavascriptExecutor) driver;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("var x = $(\'"+cssLocator+"\');");
        stringBuilder.append("x.click();");
        js.executeScript(stringBuilder.toString());
}
jsClickByCss(css);

您还可以使用构建器,高级用户互动API尝试其他方法: 这个想法很简单。首先,您应该下拉下拉列表,以便您想要点击的元素变为可见,请等待driver.manage.timeout,然后选择所需的下拉元素并单击。

WebElement mnuElement;
WebElement submnuElement;
mnEle = driver.findElement(By.Id("mnEle")).click();
sbEle = driver.findElement(By.Id("sbEle")).click();

Actions builder = new Actions(driver);
// Move cursor to the Main Menu Element
builder.MoveToElement(mnEle).perform();
// Giving 5 Secs for submenu to be displayed
Thread.sleep(5000L);
// Clicking on the Hidden SubMenu
driver.findElement(By.Id("sbEle")).click();

您可以阅读其他一些信息here 希望这适合你)

答案 2 :(得分:0)

这是Ruby的解决方案:

要从列表中选择值,需要执行javascript,这里是示例:

HTML:

<select id="select_id">
   <option id="option_id_1" value="value_1" name="OPTION1"> OPTION1 </option>
   <option id="option_id_2" value="value_2" name="OPTION2"> OPTION2 </option>

更新: 更简单的方法:  $('#select_id')。val(value_1)

代码:    按id属性查找元素:

browser.execute_script("$('#select_id').val($('#option_id_1').val())")

按名称属性查找元素:

browser.execute_script("$('#select_id').val($('option[name=OPTION2]').val())")

完美适合我。