我们如何使用Selenium WebDriver将Web列表元素存储到数组中
例如:
weblist.get(j).findElement(By.className("accordion-toggle")).getText()
它包含我们将这些元素存储到数组中的元素列表。
答案 0 :(得分:2)
您可以尝试这样
//to catch all web elements into list
List<WebElement> myList=driver.findElements(By.className("accordion-toggle"));
//myList contains all the web elements
//if you want to get all elements text into array list
List<String> all_elements_text=new ArrayList<>();
for(int i=0; i<myList.size(); i++){
//loading text of each element in to array all_elements_text
all_elements_text.add(myList.get(i).getText());
//to print directly
System.out.println(myList.get(i).getText());
}
谢谢
答案 1 :(得分:0)
假设您知道列表中的元素数量,请使用Java的List接口:
List<String> list = new ArrayList<String>();
for(j=0;j<weblist.size();J++){
list.add(weblist.get(j).findElement(By.className("accordion-toggle")).getText())
}
答案 2 :(得分:0)
您必须使用selenium webdriver的findElement
方法,而不是使用findElements
。它将直接返回Web元素列表。要使用Selenium的功能,请创建自定义方法getBy,它将使用By abstract class。
public List<WebElement> findElements(String locator, long... timeOut) {
try {
if (timeOut.length == 1 && timeOut[0] == 0) {
return driver.findElements(getBy(locator));
} else if (timeOut.length == 1 && timeOut[0] > 0) {
waitForPresent(locator, timeOut[0]);
} else {
waitForPresent(locator);
}
} catch (Exception e) {
}
return driver.findElements(getBy(locator));
}
String xPath = "xpath=//*[@text='some text']";
//String xPath = "name='some text'";
//String xPath = "id=xxxx";
private By getBy(String locator) {
locator = getProps().getString(locator, locator);
String[] parts = locator.split("=", 2);
By by = null;
switch (parts[0].trim()) {
case "xpath":
by = By.xpath(parts[1]);
break;
case "name":
by = By.name(parts[1]);
break;
case "link":
by = By.linkText(parts[1]);
break;
case "id":
by = By.id(parts[1]);
break;
case "css":
by = By.cssSelector(parts[1]);
break;
default:
throw new RuntimeException("invalid locator");
}
return by;
}
答案 3 :(得分:0)
使用weblist.size()有助于最终结果未知。因此,帮助我们创建数组列表,而不是给出明确的结束。
for(j=0;j<weblist.size();J++){