2016-01-20 28 views

回答

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()) 
} 
+0

爲什麼不'list.size()'?而不是N. – Guy

+0

@guy,你說得對.'weblist.size()'可以代替'N'。所發佈的代碼部分並不完整,所以我不想做出更多的假設。更新了答案。 – parishodak

0

改用findElement,你必須使用硒的webdriver的findElements方法。它會直接返回網頁元素列表。要使用通過硒的功能創建自定義方法getBy將使用通過抽象類。

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; 
} 
1

你可以嘗試這樣的

//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()); 

    } 

謝謝

0

使用weblist.size()時,最終結果是未知的幫助。從而幫助我們創建數組列表,而不會給出明確的結果。

for(j=0;j<weblist.size();J++){ 
相關問題