【问题标题】:Building an array from a list of options从选项列表构建数组
【发布时间】:2014-09-09 18:19:45
【问题描述】:
我目前有以下代码,它定位Show id,然后是下面option 标签中的元素,并一一打印出来。
WebElement dropDown = driver.findElement(By.id("Show"));
List<WebElement> options = dropDown.findElements(By.tagName("option"));
for (WebElement el : options) {
System.out.println(el.getAttribute("text"));
}
如何修改它,以便它构建一个包含所有文本元素的数组,而不是一个一个地打印出来?
【问题讨论】:
标签:
java
eclipse
internet-explorer
selenium
selenium-webdriver
【解决方案1】:
在 WebDriver 中,我们在 Select 类中有一个方法来获取 select 标记中可用的所有选项。
List<WebElement> options = new Select(driver.findElement(By.id("Show"))).getOptions();
要获取所有选项值数组,请遵循以下逻辑。
public String[] getOptions() {
String optionValues="";
List<WebElement> options = new Select(driver.findElement(By.id("Show"))).getOptions();
for(WebElement eachOption : options) {
optionValues+=eachOption.getText()+",";
}
return optionValues.split(",");
}
【解决方案2】:
您只需要声明另一个数组(或列表,取决于您的偏好)并更改您的 System.out.println() 语句。
对于文本属性是什么对象的列表:
for(WebElement el : options){
secondList.Add(el.getAttribute("text"));
}
对于数组,使用索引是最简单的:
for(int i = 0; i < options.Size(); i++){
secondArray[i] = options.Get(i).getAttribute("text");
}