【问题标题】:Selenium WD | How do I copy all values from a WebElement list into a String list?硒WD |如何将 WebElement 列表中的所有值复制到字符串列表中?
【发布时间】:2018-03-08 07:29:33
【问题描述】:

我有一个列表,我收集了一个不断变化的股票价格列表

列出 listOfLastPrice1;

我知道这个列表不是恒定的,因为股票的价格不是恒定的。这意味着如果我现在打印它,并在 5 分钟内再次打印它,值会改变。为什么?因为这是一个直接连接到 DOM 的 WebElement 列表。

我创建了第二个列表

ArrayList listCopyLastPrice1 = new ArrayList();

我想将 WebElement 列表中的所有值复制到字符串列表中。 我该怎么做?

我尝试了几次,但都没有成功

package TestMain;

import java.util.ArrayList;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import PageObjects.Editions;

public class Test {

public void getList(WebDriver driver) {



driver.get("https:www.investing.com/Markets");
List <WebElement> listOfLastPrice1;
listOfLastPrice1= driver.findElements(By.cssSelector("[data-column-name='last'][class*='pid']")); 

ArrayList<String> listCopyLastPrice1 = new ArrayList<String>();

//..........

}

}

【问题讨论】:

    标签: java selenium arraylist


    【解决方案1】:

    遍历WebElement 列表并将值添加到String 列表

    List <WebElement> listOfLastPrice1;
    listOfLastPrice1= driver.findElements(By.cssSelector("[data-column-name='last'][class*='pid']")); 
    
    List<String> listCopyLastPrice1 = new ArrayList<String>();
    
    for (WebElement element : listOfLastPrice1) {
        listCopyLastPrice1.add(element.getText());
    }
    

    编辑:

    从 Java 1.8 开始,您可以使用 Stream API 将 WebElements 的列表更改为 String 的列表,如下所示:

    List<String> listOfLastPrice1WithStrings = driver.findElements(By.cssSelector("[data-column-name='last'][class*='pid']"))
        .stream() 
        .map(x -> x.getText())
        .collect(Collectors.toList());
    
    

    【讨论】:

    • @dimaedunov 如果它解决了您的问题,请接受我的回答 :)
    • 刚刚做了,抱歉我是新手。简单易用的解决方案
    • @dimaedunov 很高兴,我能帮上忙。编码愉快!
    • 粗略地说,您的回答很中肯(+1)
    • @DebanjanB 我看过你的很多帖子,我认为旁白非常有用。我阅读了您的一些答案并学到了一两件事,即使如此,我还是很先进。继续做你该做的!
    【解决方案2】:

    ,您不能在 String 的 List 中复制 WebElementList 类型。尝试这将引发ClassCastException。但是您可以在 String 类型 List 中存储 WebElements 的任何属性(例如 id、name、innerText、innerHTML),如下所示:

    List<String> listCopyLastPrice1 = new ArrayList<String>();
    List<WebElement> listOfLastPrice1 = driver.findElements(By.cssSelector("[data-column-name='last'][class*='pid']"));
    for(WebElement elem:listOfLastPrice1)
        listCopyLastPrice1.add(elem.getAttribute("innerHTML"));
    System.out.println(listCopyLastPrice1);
    

    【讨论】:

    • 有可能,请参阅 Rafał Laskowski 的附加解决方案
    • @dimaedunov DebanjanB 的解决方案非常相似,看起来它也可以回答您的问题。 +1
    猜你喜欢
    • 1970-01-01
    • 2013-03-22
    • 2020-08-02
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    相关资源
    最近更新 更多