Selenium - 只能选择列表中的第一个元素,而能够打印所有元素

时间:2014-09-08 14:13:08

标签: java selenium selenium-webdriver

我正在尝试遍历下拉菜单,我能够获取每个列出的元素,但是当我使用.click().submit()命令时,它会选择第一个并执行不再继续了。我知道它要继续下去,我需要重新选择下拉箭头,这样每次提交后列表都会显示为selenium。我试着评论让它变得可读。非常感谢任何帮助。

我记下了以下内容,

WebElement search = driver.findElement(By.id("search-form"));
WebElement arrowDownButton = search.findElement(By.className("dropdown-toggle"));
arrowDownButton.click();


WebElement menu = search.findElement(By.className("dropdown-menu"));



List <WebElement> listOptions = menu.findElements(By.tagName(LI)); //selecting the listed elements , LI is "li" (declared previously)


int numberOfCountries = listOptions.size();
log("We have " + numberOfCountries + " entires");
int i=0; //for looping 
//store into an array because web elements disappear
WebElement []listOfCountries = new WebElement[listOptions.size()]; //making an array of size listed elements
for (WebElement aOption : listOptions)
{
    listOfCountries[i] = aOption; //saving the value into an array
    String dataValue = aOption.getAttribute("data-value"); // what country am I wanting click
    i++;
}

for(WebElement country : listOfCountries)
{
    log(country.getText()); //log is a another function executing System.out.println
    country.click(); //clicking on the web element
    country.submit(); // submitting the element
    arrowDownButton.click(); //reselecting the drop-down menu -> Why isn't this working?
}

}

以下是我尝试过的一些方法: 我没有直接尝试点击元素,而是创建,保存和遍历数组。但是,它也只是单击第一个元素。

以下是我收到的错误: 线程“main”中的异常org.openqa.selenium.ElementNotVisibleException:元素当前不可见,因此可能无法与arrowDownButton.click();进行交互,但我无法弄清楚为什么它无法重新定位。

2 个答案:

答案 0 :(得分:0)

for(WebElement country : listOfCountries)
{
    log(country.getText()); //log is a another function executing System.out.println
    country.click(); //clicking on the web element

    Thread.Sleep(500);
    country.submit(); // submitting the element

  // You have to reselect this element. Because doesn't make sense anymore.
  // Try reselect next element
    arrowDownButton.click(); //reselecting the drop-down menu -> Why isn't this working?

}

答案 1 :(得分:0)

看看你的下拉菜单是不在选择列表中,可能是,在这种情况下,你当前的代码不会工作。如果您可以发布尝试与之交互的webelement的Html代码,将会很有帮助。